/**
 * Created by Daniel on 2017/8/25.
 */
var AV = require('leanengine');
var gm = require('gm');
var fs = require('fs');
var im = require('imagemagick');
var multiparty = require('multiparty');
var uuid = require('node-uuid');
var imageMagick = gm.subClass({imageMagick: true});
var apis = require('../cloud/lib/apis');
var moment = require("moment");
var message = require('../cloud/lib/message');
var common = require('../cloud/common');
var rongrequest = require('../cloud/lib/rongrequest');
var crypto = require("crypto")
var qn = require("../qiniu/upload");
var qnAndroid = require("../qiniu/androidUpload");
var qiniuServer = require('../cloud/server/qiniuServer');
var app = require('../cloud/qiniu/app');
let math = require('mathjs')
var chatRoom = require('../cloud/lib/chatroom');
let rp = require('request-promise');
let request = require('request')
let remoteImageUrlDomain = 'http://tribemedia.aladada.com/';
let xlsx = require('node-xlsx')
let momenttz = require('moment-timezone')
momenttz.locale('zh-cn');

exports.findTribe = findTribe;

function findTribe(parentOId, userObj, callback) {
    var query = new AV.Query('Tribe_relation');
    query.equalTo('parentOId', parentOId);
    query.include('tribeObj');
    query.limit(1000);
    query.notEqualTo('tribeObj.creater', userObj);
    query.find().then(function (result) {
        var data = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            // if(userFindObj == userObj){
            temObj["num"] = result[i].get("tribeObj").get("num");
            temObj["name"] = result[i].get("tribeObj").get("name");
            // }
            data[i] = temObj;
        }
        callback(null, JSON.stringify(data));
    });
}

exports.userInformation = userInformation;

function userInformation(nickName, objectId, mobilePhoneNumber, uid, page, num, username, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('_User');

    if (nickName != "" && nickName != undefined && nickName != null) {
        query.contains("nickName", nickName);
    }
    if (username != "" && username != undefined && username != null) {
        query.equalTo("username", username);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }

    if (mobilePhoneNumber != "" && mobilePhoneNumber != undefined && mobilePhoneNumber != null) {
        query.equalTo("mobilePhoneNumber", mobilePhoneNumber);
    }

    if (uid != "" && uid != undefined && uid != null) {
        query.equalTo("uid", uid);
    }

    query.skip((page - 1) * num);
    query.limit(num);
    query.descending("createdAt")
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                temObj["objectId"] = result[i].id;
                temObj["sex"] = result[i].get("sex");
                temObj["uid"] = result[i].get("uid");
                temObj["username"] = result[i].get("username");
                temObj["regisFrom"] = result[i].get("regisFrom");
                temObj["gender"] = result[i].get("userAvatar") ? result[i].get("userAvatar").url() : "";
                temObj["mobilePhoneNumber"] = result[i].get("mobilePhoneNumber");
                temObj["live_authority"] = result[i].get("live_authority");
                temObj["verify_authority"] = result[i].get("verify_authority");
                temObj["authData"] = result[i].get("authData");
                temObj["createAt"] = moment(result[i].createdAt).format('YYYY-MM-DD HH:mm:ss');
                temObj["nickName"] = result[i].get("nickName");
                temObj["phoneRegVerify"] = result[i].get("phoneRegVerify");
                temObj["status"] = result[i].get("status");
                temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY-MM-DD HH:mm:ss');
                temObj["address"] = result[i].get("province") + result[i].get("city");
                temObj["province"] = result[i].get("province");
                temObj["city"] = result[i].get("city");
                temObj["qrCode"] = result[i].get("qrCode") ? result[i].get("qrCode").url() : "";
                temObj["userType"] = result[i].get("userType");
                temObj["signature"] = result[i].get("signature");
                temObj["type"] = result[i].get("type") ? result[i].get("type") : 0;
                data[i] = temObj;
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
}

exports.updataUser = updataUser;

function updataUser(req, callback) {
    var User = AV.Object.createWithoutData('_User', req.params.objectId);
    var password = req.params.password;
    let type = req.params.type;
    // 修改属性
    User.set('nickName', req.params.nickName);
    User.set('sex', req.params.sex);
    User.set('province', req.params.province);
    User.set('city', req.params.city);
    User.set('live_authority', Number(req.params.live));
    User.set('status', req.params.loginStatus);
    User.set('signature', req.params.signature);
    if (type != "" && type != undefined && type != null) {
        User.set('type', Number(type));
    }

    if (password != "" && password != undefined && password != null) {
        User.set('signature', req.params.signature);
    }
    // 保存到云端
    User.save().then(function (success) {
        let url = "http://health.aladada.com/user/userTj?userId="+req.params.objectId
          request(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
              // console.log(body) // Show the HTML for the baidu homepage.
              callback(null, success);
            } else {
              callback(error, null);
            }
          })
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
}

function addUser() {
    var User = AV.Object.extend('_User');
    var user = new User();
    user.set();
    user.save().then(function (result) {

    })
}


exports.userStatus = userStatus;

function userStatus(name, tel, objectId, status, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_account_verify');

    if (name != "" && name != undefined && name != null) {
        query.equalTo("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }

    if (tel != "" && tel != undefined && tel != null) {
        query.equalTo("tel", tel);
    }

    if (status != "" && status != undefined && status != null) {
        query.equalTo("status", status);
    }

    query.skip((page - 1) * num);
    query.limit(num);
    query.descending('createdAt');
    query.find().then(function (result) {
        var obj = {};
        var data = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["objectId"] = result[i].id;
            temObj["identityCardNo"] = result[i].get("identityCardNo");
            temObj["tel"] = result[i].get("tel");
            temObj["name"] = result[i].get("name");
            temObj["holdIdentityCard"] = result[i].get("holdIdentityCard") ? result[i].get("holdIdentityCard").url() : "";
            temObj["reason"] = result[i].get("reason");
            temObj["status"] = result[i].get("status");
            temObj["createdAt"] = moment(result[i].createdAt).format('YYYY-MM-DD HH:mm:ss');
            data[i] = temObj;
        }
        query.count().then(function (count) {
            obj.data = data;
            obj.total = count;
            callback("null", obj);
        })
    })
}

exports.updataUserStatus = updataUserStatus;

function updataUserStatus(req, callback) {
    var User = AV.Object.createWithoutData('Shop_account_verify', req.params.objectId);
    // 修改属性
    User.set('name', req.params.name);
    User.set('tel', req.params.tel);
    User.set('identityCardNo', req.params.identityCardNo);
    User.set('reason', req.params.reason);
    User.set('status', req.params.status);
    User.set('shopStatus', req.params.status);
    // 保存到云端
    User.save().then(function (success) {
            callback(null, success);
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
}

exports.getShopVerifyInfo = getShopVerifyInfo;

function getShopVerifyInfo(params, callback) {
    var page = params.pageIndex;
    var num = params.pageSize;
    var verifyUserID = params.verifyUserID;
    var verifyUserName = params.verifyUserName;
    var verifyUserIdentityCardNo = params.verifyUserIdentityCardNo;
    var verifyUserTel = params.verifyUserTel;
    var shopStatus = params.shopStatus;
    if (shopStatus == '-1') {
        shopStatus = '';
    }
    var query = new AV.Query('Shop_account_verify');

    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }

    if (verifyUserID != "" && verifyUserID != undefined && verifyUserID != null) {
        query.equalTo("userOId", verifyUserID);
    }
    if (verifyUserName != "" && verifyUserName != undefined && verifyUserName != null) {
        query.contains("name", verifyUserName);
    }
    if (verifyUserIdentityCardNo != "" && verifyUserIdentityCardNo != undefined && verifyUserIdentityCardNo != null) {
        query.contains("identityCardNo", verifyUserIdentityCardNo);
    }
    if (verifyUserTel != "" && verifyUserTel != undefined && verifyUserTel != null) {
        query.contains("tel", verifyUserTel);
    }
    if (shopStatus != "" && shopStatus != undefined && shopStatus != null) {
        query.equalTo('shopStatus', shopStatus);
    }
    query.skip(page * num);
    query.limit(num);
    query.descending('updatedAt');

    query.find().then(function (shops) {
        query.count().then(function (count) {
            var returnObject = {};
            var array = [];
            for (var i = 0; i < shops.length; i++) {
                var obj = {};
                obj.objectId = shops[i].id;
                obj.userOId = shops[i].get('userOId');
                obj.name = shops[i].get('name');
                obj.holdIdentityCard = shops[i].get('holdIdentityCard') ? shops[i].get('holdIdentityCard').url() : "";
                obj.identityCardNo = shops[i].get('identityCardNo');
                obj.tel = shops[i].get('tel');
                obj.shopStatus = shops[i].get('shopStatus');
                obj.reason = shops[i].get('reason');

                obj.createdAt = moment(shops[i].createdAt).format('YYYY-MM-DD HH:mm:ss');//创建时间
                obj.updatedAt = moment(shops[i].updatedAt).format('YYYY-MM-DD HH:mm:ss');//更新时间
                array.push(obj);
            }
            ;
            returnObject.data = array;
            returnObject.total = count;
            return callback(returnObject);
        });

    }, function (error) {
        console.log(error.message);
        callback(error.message);
    });
};
exports.shopVerifyMangerEditHandle = shopVerifyMangerEditHandle;

function shopVerifyMangerEditHandle(params, callback) {
    var ifAgree = params.shopStatus;
    if (!params.objectId && !params.userOId && !params.shopStatus) {
        callback("错误的参数!")
    }
    var objectId = params.objectId;
    var toUserOId = params.userOId;
    var content;
    if (ifAgree == '2') {
        content = "掌柜的：您申请的店铺审批未通过。原因是" + params.reason;
        ifAgree = '4';
    } else {
        content = "掌柜的：您申请的店铺审批已通过。";
        ifAgree = '1';
    }
    // 推送交易消息
    var msg_content = {};
    msg_content["content"] = content;

    var msg_extra = {};
    msg_extra["extra"] = apis['message_profession_code']['tribe_sys_code']; //交易消息代码
    msg_extra["code"] = apis['message_type_code']['word']; //文本消息
    msg_extra["content"] = msg_content;

    var base64Content = new Buffer(JSON.stringify(msg_extra)).toString('base64');
    base64Content = base64Content.replace(/\+/g, "@");
    base64Content = base64Content.replace(/\=/g, "");

    var sendObj = {};
    sendObj["operation"] = "";
    sendObj["sourceUserId"] = "";
    sendObj["targetUserId"] = "";
    sendObj["extra"] = base64Content;
    message.publish("admin", toUserOId, "RC:ContactNtf", JSON.stringify(sendObj), "json", function (err, result1) {
    });
    //记录到系统消息中
    var SystemMessage = AV.Object.extend('SystemMessage');
    var targetUserObj = AV.Object.createWithoutData('_User', toUserOId);
    var systemMessage = new SystemMessage;
    systemMessage.set('targetUserOId', toUserOId);
    systemMessage.set('targetUserObj', targetUserObj);
    systemMessage.set('sendUserObj', params.user);
    systemMessage.set('sortTime', common.getCurrTime());
    systemMessage.set('title', '123456');
    systemMessage.set('status', 0);
    systemMessage.set('messageType', 1);
    systemMessage.set('content', msg_content['content']);
    systemMessage.save()
    if (ifAgree != '2') {
        var queryS = new AV.Query('Shop_goods');
        queryS.equalTo('sellerOId', toUserOId);
        queryS.equalTo('status', 2);
        queryS.find().then(function (goods) {
            if (goods) {
                for (var i = 0; i < goods.length; i++) {
                    goods[i].set("status", 1);
                }
                AV.Object.saveAll(goods, function (list, error) {
                });
            }
        }, function (err) {
        })
    }

    var query = new AV.Query('Shop_account_verify');
    query.equalTo('objectId', objectId);
    query.first().then(function (shop) {
        shop.set('shopStatus', ifAgree);
        shop.set('status', ifAgree);
        shop.set('reason', params.reason);
        shop.save().then(function (shop) {
            callback("success");
        }, function (error) {
            callback(error.message);
        })
    }, function (error) {
        callback(error.message);
    })
};
exports.shopInformation = shopInformation;

function shopInformation(objectId, name, type, page, num, callback) {

    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_shop');

    if (name != "" && name != undefined && name != null) {
        query.contains("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (type != "" && type != undefined && type != null) {
        query.equalTo("type", type);
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('userObj');
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(function (count) {
                var obj = {};
                var data = [];
                var num = 0;
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    num++;
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["sellNum"] = result[i].get("sellNum");
                    temObj["phone"] = result[i].get("phone");
                    temObj["name"] = result[i].get("name");
                    temObj["username"] = result[i].get("userObj") ? result[i].get("userObj").get("nickName") : "";
                    temObj["icon"] = result[i].get("icon") ? result[i].get("icon").url() : "";
                    temObj["type"] = result[i].get("type");
                    temObj["searchVal"] = result[i].get("searchVal");
                    temObj["status"] = result[i].get("status");
                    temObj["collectionNum"] = result[i].get("collectionNum");
                    temObj["userOId"] = result[i].get("userOId");
                    temObj["introduction"] = result[i].get("introduction");
                    temObj["showType"] = result[i].get("showType");
                    temObj["orderNoReceiveCount"] = result[i].get("orderNoReceiveCount");
                    temObj["orderCancelCount"] = result[i].get("orderCancelCount");
                    temObj["createdAt"] = moment(result[i].createdAt).format('YYYY-MM-DD HH:mm:ss');
                    temObj["creditScore"] = result[i].get("creditScore");

                    data.push(temObj);

                }
                obj.data = data;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            console.log(error)
            callback(error, null);
        }
    )
}

exports.updataShopInformation = updataShopInformation;

function updataShopInformation(req, callback) {
    var objectId = req.params.objectId;
    if (objectId != "" && objectId != undefined && objectId != null) {
        var Shop = AV.Object.createWithoutData('Shop_shop', objectId);
    } else {
        var shopShop = AV.Object.extend('Shop_shop');
        var Shop = new shopShop();
        var userObj = AV.Object.createWithoutData('_User', req.params.userId);
        Shop.set('userObj', userObj);
        Shop.set('userOId', req.params.userId);
    }
    // 修改属性
    Shop.set('name', req.params.name);
    Shop.set('showType', req.params.showType);
    Shop.set('introduction', req.params.introduction);
    Shop.set('status', req.params.status);
    Shop.set('type', req.params.type);
    // 保存到云端
    Shop.save().then(function (success) {
            callback("null", success);
        }, function (error) {
            console.log(error);
        }
    )
}

exports.shopType = shopType;

function shopType(callback) {
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode", '0');
    query.find().then(function (result) {
        var resultArr = [];
        var fatherObj = {name: "店铺分类", id: "xz", expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["name"] = result[i].get("name");
            temObj["pid"] = "xz";
            resultArr.push(temObj);
        }
        callback(resultArr)
    }, function (error) {
        console.log(error);
        callback(error);
    })
}

exports.tribeList = tribeList;

function tribeList(page, num, name) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }

    let query = new AV.Query('Tribe');
    if (name != "" && name != undefined && name != null) {
        query.contains("name", name);
    }

    query.skip((page - 1) * num);
    query.limit(num);
    query.exists('createrObj');
    return query.find().then(function (result) {
        return query.count().then(count => {
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {
                    objectId: item.id,
                    name: item.get('name')
                }
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count
            return obj
        }).catch(error => {
            return null
        })

    }).catch(error => {
        return null;
    })
}

exports.saveTribeLive = saveTribeLive;

function saveTribeLive(req) {
    let TribeLive = AV.Object.extend('Tribe_live')
    let {liveObjectId} = req.params;
    console.log(liveObjectId, "========liveObjectId")
    let liveObj = AV.Object.createWithoutData('Live_room', liveObjectId);
    let array = [];
    for (let tribeOId of req.params.tribeList) {
        let tribeObj = AV.Object.createWithoutData('Tribe', tribeOId);
        let tribeLive = new TribeLive();
        tribeLive.set("tribeOId", tribeOId);
        tribeLive.set("liveOId", liveObjectId);
        tribeLive.set("tribeObj", tribeObj);
        tribeLive.set("liveObj", liveObj);
        tribeLive.save().then(function (data) {
            return data;
        })
        array.push(tribeLive)
    }
    return Promise.all(array).then(values => {
        return values;
    }).catch(error => {
        console.log(error);
        return
    })
}

exports.shopTypeSelect = shopTypeSelect;

function shopTypeSelect(callback) {
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode", '0');
    query.find().then(function (result) {
        var resultArr = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["text"] = result[i].get("name");
            resultArr.push(temObj);
        }
        callback(resultArr);
    }, function (error) {
        console.log(error);
        callback(error, null);
    })
}

exports.goodsTypeSelect = goodsTypeSelect;

function goodsTypeSelect(callback) {
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode", '0');
    query.find().then(function (result) {
        var resultArr = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["text"] = result[i].get("name");
            temObj["objectId"] = result[i].get("objectId");
            resultArr.push(temObj);
        }
        callback(resultArr);
    }, function (error) {
        console.log(error);
        callback(error, null);
    })
}

AV.Cloud.define("userInformation", function (req, res) {
    userInformation(req.params.key, req.params.objectId, req.params.mobilePhoneNumber, req.params.page, req.params.num, function (error, result) {
        return res.success(result)
    })
});


exports.goodsInformation = goodsInformation;

function goodsInformation(objectId, shopOId, title, goodsType, status, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_goods');


    if (shopOId != "" && shopOId != undefined && shopOId != null) {
        query.equalTo("shopOId", shopOId);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (title != "" && title != undefined && title != null) {
        query.contains("title", title);
    }
    if (goodsType != "" && goodsType != undefined && goodsType != null) {
        query.equalTo("shop_good_type_OId", goodsType);
    }
    if (status != "" && status != undefined && status != null) {
        query.equalTo("status", Number(status));
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('shopObj');
    query.include('shop_good_type_Obj');
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(async function (count) {
                var obj = {};
                var data = [];
                var qn = 'http://tribemedia.aladada.com/';
                // var picOIdArr=[];
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["recommend"] = result[i].get("recommend");//店长推荐
                    temObj["groupBuying"] = result[i].get("groupBuying");//能否团购
                    temObj["promotePrice"] = result[i].get("promotePrice");//推广佣金
                    temObj["shopName"] = result[i].get("shopObj") ? result[i].get("shopObj").get("name") : "";
                    temObj["groupPrice"] = result[i].get("groupPrice");
                    temObj["saleNums"] = result[i].get("saleNums");//销量
                    temObj["title"] = result[i].get("title");//名称
                    temObj["originalPrice"] = result[i].get("originalPrice");//原价
                    temObj["status"] = result[i].get("status");//-1删除 0下架 1上架
                    temObj["freePost"] = result[i].get("freePost");//包邮
                    temObj["shopOId"] = result[i].get("shopOId");//店铺Id
                    // temObj["describe"] = result[i].get("describe");//描述
                    let describeText = result[i].get("describe");//描述
                    let reg=/<[^<>]+>/g
                    temObj["describe"] = describeText.replace(reg,'')
                    temObj["discount"] = result[i].get("discount");//折扣
                    temObj["price"] = result[i].get("price");//价格
                    temObj["customize"] = result[i].get("customize");//订制 1可以 -1不可以
                    temObj["stock"] = result[i].get("stock");//库存
                    temObj["goodsType"] = result[i].get("shop_good_type_Obj") ? result[i].get("shop_good_type_Obj").get("name") : "";//商品分类
                    temObj["goodsTypeOId"] = result[i].get("shop_good_type_OId") ? result[i].get("shop_good_type_OId") : "";//商品分类OId
                    temObj["createdAt"] = moment(result[i].createdAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["shopIcon"] = result[i].get("picName") ? qn + result[i].get("picName") : "";
                    if (objectId){
                        if (result[i].get("picArray")){

                            let picArray = []
                            result[i].get("picArray").forEach(item=>{
                                picArray.push(item.id)
                            })
                            let shopGoodsPicQuery = new AV.Query('Shop_goodsPic')
                            shopGoodsPicQuery.containedIn('objectId',picArray)
                            shopGoodsPicQuery.ascending('sortNum')
                            shopGoodsPicQuery.find().then(shopGoodsPics=>{
                                var shopGoodsPicArray =[]
                                shopGoodsPics.forEach(shopGoodsPic=>{
                                    let shopGoodsPicUrl = qn+shopGoodsPic.get('picName')+'?imageMogr2/thumbnail/640x/format/jpg/interlace/1/auto-orient'
                                    let tempDic = {}
                                    tempDic.shopGoodsPicUrl = shopGoodsPicUrl
                                    tempDic.sortNum = shopGoodsPic.get('sortNum')
                                    shopGoodsPicArray.push(tempDic)
                                })
                                temObj["shopGoodsPicArray"] = shopGoodsPicArray
                            }).catch(error=>{
                                console.log('error:',error)
                            })
                        }
                    }
                    data.push(temObj);
                }
                obj.data = data;
                obj.total = count;
                callback("null", obj);
            }).catch(err => {
                console.log(err);
            })
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
}

exports.getGoodsEditModelArray = getGoodsEditModelArray;
function getGoodsEditModelArray(objectId, callback) {
    if (objectId != "" && objectId != undefined && objectId != null) {
        var query = new AV.Query('Shop_goods');
        query.equalTo("objectId", objectId);
    } else {
        callback('请提供ObjectId!')
    }
    query.first().then(async result => {
        if (result.get("modelArray")) {
            var modelIdArray = result.get("modelArray").map(item => {
                return item.id
            })
        }
        var modelData = []
        if (modelIdArray && modelIdArray.length > 0) {
            var modelQuery = new AV.Query('Shop_goods_model_stock');
            modelQuery.descending('createdAt')
            modelQuery.containedIn('objectId', modelIdArray)
            await modelQuery.find().then(modelItems => {
                modelData = modelItems.map(modelItem => {
                    return {
                        modelId: modelItem.id,
                        stock: modelItem.get('stock'),
                        model: modelItem.get('model'),
                    }
                })
                callback(modelData)
            }).catch(modelErr => {
                console.log(modelErr)
            })
        } else {
            callback(modelData)
        }
    }).catch(error => {
    })
}
exports.saveModelForUpdateGoods = saveModelForUpdateGoods;
async function saveModelForUpdateGoods(goodsOId, models) {
    let query = new AV.Query("Shop_goods_model_stock")
    query.equalTo('goodsOId', goodsOId)

    return new Promise(rs => {
        query.find().then(res => {
            rs(res)
        })
    }).then(res => {
        return new Promise(rs => {
            AV.Object.destroyAll(res).then(cc => {
                rs(false)
            }).catch(err => {
                rs(err)
            })

        })

    }).then(res=>{
        if (!res){
            var GoodsModel = AV.Object.extend('Shop_goods_model_stock');
            var modelArr = [];
            for (let i = 0; i < models.length; i++) {
                var goodsModel = new GoodsModel();
                var goodsObj = AV.Object.createWithoutData("Shop_goods", goodsOId)
                goodsModel.set("stock", Number(models[i].stock));
                goodsModel.set("model", models[i].model);
                goodsModel.set("goodsOId", goodsOId);
                goodsModel.set("goodsObj", goodsObj);
                goodsModel.set("sortNum", i + 1)
                modelArr.push(goodsModel);
            }
            return AV.Object.saveAll(modelArr).then((pic) => {
                return modelArr;
            }, (reject) => {
                console.log("-----------------------------" + reject)
                return false
            })
        }
    })


}

exports.updataGoodsInformation = updataGoodsInformation;

async function updataGoodsInformation(req, callback) {
    var picArr = JSON.parse(req.params.downUrl);
    var model = JSON.parse(req.params.model);
    var goodsId = await saveGoods(req);
    // console.log(goodsId)
    var picIdArr = await savePic(picArr, goodsId);
    var modelArray = await saveModel(model, goodsId);
    var goods = AV.Object.createWithoutData("Shop_goods", goodsId);
    goods.set("picArray", picIdArr);
    goods.set("modelArray", modelArray);
    goods.save().then((result) => {
        callback(null, "10001")
    }, (reject) => {
        console.log(reject);
    })

    function saveGoods(req) {
        var objectId = req.params.objectId;
        if (objectId != "" && objectId != undefined && objectId != null) {
            var Shop = AV.Object.createWithoutData('Shop_goods', req.params.objectId);
        } else {
            var Shops = AV.Object.extend('Shop_goods');
            var Shop = new Shops();
            var shopObj = AV.Object.createWithoutData('Shop_shop', req.params.shopOId);
            var sellerObj = AV.Object.createWithoutData('_User', req.params.sellerOId);
            Shop.set('shopOId', req.params.shopOId);
            Shop.set('shopObj', shopObj);
            Shop.set('sellerOId', req.params.sellerOId);
            Shop.set('sellerObj', sellerObj);
            Shop.set("picName", picArr[0]);
        }
        // 修改属性
        Shop.set('title', req.params.title);
        Shop.set('promotePrice', Number(req.params.promotePrice));
        Shop.set('status', Number(req.params.status));
        Shop.set('groupBuying', Number(req.params.groupBuying));
        Shop.set('freePost', req.params.freePost);
        Shop.set('groupPrice', Number(req.params.groupPrice));
        Shop.set('saleNums', Number(req.params.saleNums));
        Shop.set('originalPrice', Number(req.params.originalPrice));
        Shop.set('price', Number(req.params.price));
        Shop.set('customize', Number(req.params.customize));
        Shop.set('discount', Number(req.params.discount));
        Shop.set('describe', req.params.describe);
        Shop.set('stock', Number(req.params.stock));
        let goodsTypeOId = req.params.goodsTypeOId
        if (goodsTypeOId != "" && goodsTypeOId != undefined && goodsTypeOId != null) {
            var shop_good_type_Obj = AV.Object.createWithoutData('Shop_good_type', goodsTypeOId);
            Shop.set('shop_good_type_OId', goodsTypeOId);
            Shop.set('shop_good_type_Obj', shop_good_type_Obj);
        }
        // 保存到云端
        return Shop.save().then(function (goods) {
                return goods.id
            }, function (error) {
                console.log(error);
                return error
            }
        )
    }

    function savePic(picArr, goodsOId) {
        var GoodsPic = AV.Object.extend('Shop_goodsPic');
        var goodsArr = [];
        for (let i = 0; i < picArr.length; i++) {
            var goodsPic = new GoodsPic();
            goodsPic.set("picName", picArr[i])
            goodsPic.set("goodsOId", goodsOId)
            goodsPic.set("sortNum", i + 1)
            goodsArr.push(goodsPic);
        }
        return AV.Object.saveAll(goodsArr).then((pic) => {
            return goodsArr;
        })

    }

    function saveModel(model, goodsOId) {
        var GoodsModel = AV.Object.extend('Shop_goods_model_stock');
        var modelArr = [];
        for (let i = 0; i < model.length; i++) {
            var goodsModel = new GoodsModel();
            var goodsObj = AV.Object.createWithoutData("Shop_goods", goodsOId)
            goodsModel.set("stock", Number(model[i].stock));
            goodsModel.set("model", model[i].model);
            goodsModel.set("goodsOId", goodsOId);
            goodsModel.set("goodsObj", goodsObj);
            goodsModel.set("sortNum", i + 1)
            modelArr.push(goodsModel);
        }
        return AV.Object.saveAll(modelArr).then((pic) => {
            return modelArr;
        }, (reject) => {
            console.log("-----------------------------" + reject)

        })

    }
}

// function updataGoodsInformation(req,callback) {
//     var objectId = req.params.objectId;
//     if(objectId!=""&&objectId!=undefined&&objectId!=null){
//         var Shop = AV.Object.createWithoutData('Shop_goods',req.params.objectId);
//     }else{
//         var Shops = AV.Object.extend('Shop_goods');
//         var Shop = new Shops;
//         var shopObj = AV.Object.createWithoutData('Shop_shop', req.params.shopOId);
//         Shop.set('shopOId', req.params.shopOId);
//         Shop.set('shopObj', shopObj);
//     }
//     // 修改属性
//     Shop.set('title', req.params.title);
//     Shop.set('promotePrice',Number(req.params.promotePrice));
//     Shop.set('status', Number(req.params.status));
//     Shop.set('groupBuying', Number(req.params.groupBuying));
//     Shop.set('freePost', req.params.freePost);
//     Shop.set('groupPrice',  Number(req.params.groupPrice));
//     Shop.set('saleNums', Number(req.params.saleNums));
//     Shop.set('originalPrice', Number(req.params.originalPrice));
//     Shop.set('price', Number(req.params.price));
//     Shop.set('customize', Number(req.params.customize));
//     Shop.set('discount', Number(req.params.discount));
//     Shop.set('describe', req.params.describe);
//     Shop.set('stock',Number(req.params.stock));
//     // 保存到云端
//     Shop.save().then(function (success) {
//             callback(null,success);
//         },function (error) {
//             console.log(error);
//             callback(error,null);
//         }
//     )
// }





exports.goodsType = goodsType;

function goodsType(callback) {
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode", '0');
    query.find().then(function (result) {
        var resultArr = [];
        var fatherObj = {name: "商品分类", id: "xz", expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["name"] = result[i].get("name");
            temObj["objectId"] = result[i].get("objectId");
            temObj["pid"] = "xz";
            resultArr.push(temObj);
        }
        callback(resultArr)
    }, function (error) {
        console.log(error);
        callback(error);
    })
    // var query = new AV.Query('Shop_good_type');
    // // query.equalTo("fatherCode",'0');
    // query.addAscending('fatherCode');
    // query.find().then(function (result) {
    //
    //     var resultArr = [];
    //     var fatherObj = {name: "商品", id: 0, expanded: true};
    //     var childObj = {name: "店铺全部商品", pid: 0};
    //     resultArr.push(fatherObj);
    //     resultArr.push(childObj);
    //     for (var i = 0; i < result.length; i++) {
    //         var temObj = {};
    //         temObj["id"] = result[i].get("code");
    //         temObj["name"] = result[i].get("name");
    //         temObj["pid"] = result[i].get("fatherCode");
    //     }
    //   console.log(resultArr)
    //     callback(resultArr)
    // }, function (error) {
    //     console.log(error)
    // })
}


exports.levelType = levelType;

function levelType(fatherId, name, objectId, callback) {
    var query = new AV.Query('Dictionary_tree');
    // query.equalTo("fatherCode",'0');
    if (fatherId != "" && fatherId != undefined && fatherId != null) {
        query.equalTo('fatherId', fatherId);
    }
    if (name != "" && name != undefined && name != null) {
        query.equalTo('name', name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo('objectId', objectId);
    }
    query.descending('updatedAt');
    query.find().then(function (result) {
        var resultArr = [];
        var resultArrTree = [];
        var fatherObj = {name: "根节点", id: 0, expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].id;
            temObj["name"] = result[i].get("name");
            temObj["pid"] = result[i].get("fatherId");
            temObj["fatherName"] = result[i].get("fatherName");
            resultArr.push(temObj);
            resultArrTree.push(temObj);
        }
        callback(resultArr, resultArrTree)
    }, function (error) {
        console.log(error)
    })
}

exports.levelTypeInformation = levelTypeInformation;

function levelTypeInformation(callback) {
    var query = new AV.Query('Dictionary_tree');
    query.descending('createdAt');
    query.find().then(function (result) {
        var resultArr = [];
        var fatherObj = {id: 0, text: "根节点"};
        var treeArr = [];
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].id;
            temObj["text"] = result[i].get("name");
            temObj["pid"] = result[i].get("fatherId");
            temObj["fatherName"] = result[i].get("fatherName");
            resultArr.push(temObj);
            treeArr.push(temObj)
        }
        callback(resultArr, treeArr);
    }, function (error) {
        console.log(error)
    })
}

exports.addUserLevel = addUserLevel;

function addUserLevel(req, callback) {
    var objectId = req.params.objectId;
    if (objectId != "" && objectId != undefined && objectId != null) {
        var User = AV.Object.createWithoutData('Dictionary_tree', req.params.objectId);
    } else {
        var Users = AV.Object.extend('Dictionary_tree');
        var User = new Users;
    }
    // 修改属性
    User.set('name', req.params.name);
    User.set('fatherId', req.params.fatherId);
    User.set('fatherName', req.params.fatherName);
    // 保存到云端
    User.save().then(function (success) {
            callback(success);
        }, function (error) {
            console.log(error);
        }
    )
}


exports.userLevelInformation = userLevelInformation;

function userLevelInformation(objectId, name, levelOId, weChat, idCard, authCode, status, page, num, callback) {

    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Authorization_certificate');

    if (name != "" && name != undefined && name != null) {
        query.contains("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (levelOId != "" && levelOId != undefined && levelOId != null) {
        query.equalTo("levelOId", levelOId);
    }
    if (weChat != "" && weChat != undefined && weChat != null) {
        query.equalTo("weChat", weChat);
    }
    if (idCard != "" && idCard != undefined && idCard != null) {
        query.equalTo("idCard", idCard);
    }
    if (authCode != "" && authCode != undefined && authCode != null) {
        query.equalTo("authCode", authCode);
    }
    if (status != "" && status != undefined && status != null) {
        query.equalTo("status", status);
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('levelObj');
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(function (count) {
                var obj = {};
                var data = [];
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["telephone"] = result[i].get("telephone");
                    temObj["weChat"] = result[i].get("weChat");
                    temObj["name"] = result[i].get("name");
                    temObj["levelName"] = result[i].get("levelObj") ? result[i].get("levelObj").get("name") : "";
                    temObj["levelOId"] = result[i].get("levelObj") ? result[i].get("levelObj").get("objectId") : "";
                    temObj["teamLeader"] = result[i].get("teamLeader");
                    temObj["authCode"] = result[i].get("authCode");
                    temObj["idCard"] = result[i].get("idCard");
                    temObj["status"] = result[i].get("status");
                    temObj["createdAt"] = moment(result[i].createdAt).format('YYYY-MM-DD HH:mm:ss');
                    temObj["startPowerTime"] = result[i].get("startPowerTime");
                    temObj["endPowerTime"] = result[i].get("endPowerTime");
                    temObj["authImage"] = result[i].get("authImage");
                    var nowTime = Date.parse(new Date());
                    var startPowerTime = Date.parse(temObj["startPowerTime"]);
                    var endPowerTime = Date.parse(temObj["endPowerTime"]);
                    if (nowTime >= startPowerTime && nowTime <= endPowerTime) {
                        temObj["nowTime"] = '1';
                    } else {
                        temObj["nowTime"] = '0';
                    }
                    data.push(temObj);
                }
                obj.data = data;
                obj.total = count;
                callback("null", obj);
            })
        }, function (error) {
            console.log("aaaa")
        }
    )
}

exports.addUserLevelInformation = addUserLevelInformation;

function addUserLevelInformation(req, callback) {
    var objectId = req.params.objectId;
    // 修改属性
    if (objectId != "" && objectId != undefined && objectId != null) {
        var User = AV.Object.createWithoutData('Authorization_certificate', objectId);
    } else {
        var Users = AV.Object.extend('Authorization_certificate');
        var User = new Users;
        User.set('authCode', req.params.authCode);
    }
    var level = req.params.level;
    if (level != "" && level != undefined && level != null) {
        var levelObj = AV.Object.createWithoutData('Dictionary_tree', level);
        User.set('levelObj', levelObj);
        User.set('levelOId', req.params.level);
    }
    if (req.params.startPowerTime != null && req.params.endPowerTime != null) {
        var startPowerTime = new Date(req.params.startPowerTime);
        var endPowerTime = new Date(req.params.endPowerTime);
        User.set('startPowerTime', startPowerTime);
        User.set('endPowerTime', endPowerTime);
    }
    User.set('name', req.params.name);
    User.set('status', req.params.status);
    User.set('idCard', req.params.idCard);
    User.set('weChat', req.params.weChat);
    User.set('telephone', req.params.telephone);
    User.set('teamLeader', req.params.teamLeader);
    // 保存到云端
    User.save().then(function (success) {
            callback(success);
        }, function (error) {
            console.log(error);
        }
    )
}

exports.levelRemove = levelRemove;

function levelRemove(objectId, callback) {
    var query = new AV.Query('Dictionary_tree');
    query.equalTo("fatherId", objectId);
    query.limit(10);
    query.count().then(function (count) {
        if (count > 0) {
            callback('2')
        } else {
            var User = new AV.Query('Authorization_certificate');
            User.equalTo("levelOId", objectId);
            User.limit(10);
            User.count().then(function (num) {
                if (num > 0) {
                    callback('0')
                } else {
                    var todo = AV.Object.createWithoutData('Dictionary_tree', objectId);
                    todo.destroy().then(function (success) {
                        callback('1')
                    }, function (error) {
                        callback(error)
                    });
                }
            });
        }
    })
}

exports.getRegUserDefault = getRegUserDefault

function getRegUserDefault(page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || page == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    let query = new AV.Query('Reg_user_default');
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('userObj');
    query.ascending('createAt');
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let userObj = item.get('userObj');
                let temObj = {};
                temObj["id"] = item.get("objectId");
                temObj["objectId"] = userObj ? userObj.get("objectId") : '';
                temObj["nickName"] = userObj ? userObj.get("nickName") : '';
                temObj["userAvatar"] = userObj ? userObj.get("userAvatar").url() : '';
                temObj["createdAt"] = moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.getUserMember = getUserMember

function getUserMember(name, objectId, page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('_User');

    if (name != "" && name != undefined && name != null) {
        query.contains('nickName', name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.ascending('createdAt');

    return query.find().then(function (result) {
        return query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {}
                temObj["objectId"] = item.get("objectId");
                temObj["nickName"] = item.get("nickName");
                temObj["userAvatar"] = item.get("userAvatar") ? item.get("userAvatar").url() : "";
                temObj["createdAt"] = moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj
        })
    })
}


exports.findUserMember = findUserMember

function findUserMember(objectId) {
    let query = new AV.Query('Reg_user_default');
    if (objectId != '' || objectId != null || objectId != undefined) {
        query.equalTo('userOId', objectId);
    }
    return query.first().then(function (result) {
        return result;
    })
}

exports.findUserLevel = findUserLevel;

function findUserLevel(objectId, callback) {
    var query = new AV.Query('Authorization_certificate');

    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.include("levelObj");
    query.first().then(function (result) {
            var temObj = {};
            temObj["objectId"] = result.id
            temObj["telephone"] = result.get("telephone") ? result.get("telephone").substr(0, 7) + "****" : "";
            temObj["weChat"] = "****" + result.get("weChat").substr(4);
            temObj["name"] = result.get("name");
            temObj["levelName"] = result.get("levelObj") ? result.get("levelObj").get("name") : "";
            temObj["teamLeader"] = result.get("teamLeader");
            temObj["authCode"] = result.get("authCode").substr(0, 2) + "- " + result.get("authCode").substr(-6);
            temObj["idCard"] = result.get("idCard").substr(0, 4) + "**********" + result.get("idCard").substr(-4, 4);
            temObj["startPowerTime"] = result.get("startPowerTime");
            temObj["endPowerTime"] = result.get("endPowerTime");
            var startPowerTime = formatDateTime(temObj["startPowerTime"]);
            var endPowerTime = formatDateTime(temObj["endPowerTime"]);
            temObj["resultTime"] = startPowerTime + "-" + endPowerTime;
            callback(null, temObj);
        }, function (error) {
            console.log(error)
            callback(error, null);

        }
    )
}

exports.insertRegUserDefault = insertRegUserDefault

function insertRegUserDefault(objectId) {
    let UserDefault = AV.Object.extend('Reg_user_default');
    let userDefault = new UserDefault();
    let userQuery = AV.Object.createWithoutData('_User', objectId);
    userDefault.set('userOId', objectId);
    userDefault.set('userObj', userQuery);
    return userDefault.save().then(function (result) {
        return result;
    })
}

exports.regUserRemove = regUserRemove

function regUserRemove(objectId) {
    if (objectId != '' || objectId != undefined || objectId != null) {
        var regUser = AV.Object.createWithoutData('Reg_user_default', objectId);
        return regUser.destroy().then(res => {
            return res
        }).catch(error => {
            console.log(error)
        })
    }
}

exports.updateUserAuthImage = updateUserAuthImage;

function updateUserAuthImage(objectId, authImage, callback) {
    if (objectId != "" && objectId != undefined && objectId != null) {
        var User = AV.Object.createWithoutData('Authorization_certificate', objectId);
    }
    // 修改属性
    User.set('authImage', authImage);
    // 保存到云端
    User.save().then(function (success) {
            callback("null", success);
        }, function (error) {
            console.log(error);
        }
    )
}

exports.findAuthImage = findAuthImage;

function findAuthImage(key, callback) {
    var weChatQuery = new AV.Query('Authorization_certificate');
    weChatQuery.equalTo("weChat", key);
    weChatQuery.equalTo("status", '1');
    var idCardQuery = new AV.Query('Authorization_certificate');
    idCardQuery.equalTo("idCard", key);
    idCardQuery.equalTo("status", '1');
    var authCodeQuery = new AV.Query('Authorization_certificate');
    authCodeQuery.equalTo("authCode", key);
    authCodeQuery.equalTo("status", "1");
    var telephoneQuery = new AV.Query('Authorization_certificate');
    telephoneQuery.equalTo("telephone", key);
    telephoneQuery.equalTo("status", "1");
    var query = AV.Query.or(weChatQuery, idCardQuery, authCodeQuery, telephoneQuery);
    query.first().then(function (result) {
            if (result == undefined) {
                callback("undefined", result);
            }
            var temObj = {};
            var nowTime = Date.parse(new Date());
            var startPowerTime = Date.parse(result.get("startPowerTime"));
            var endPowerTime = Date.parse(result.get("endPowerTime"));
            //授权过期时间
            if (nowTime <= startPowerTime || nowTime >= endPowerTime) {
                callback("undefined", result);
            } else {
                temObj["authImage"] = result.get("authImage");
                callback("null", temObj);
            }
        }, function (error) {
            console.log("aaaa")
        }
    )
}

exports.shopOrderList = shopOrderList;

async function shopOrderList(objectId, name, status, receiver, orderCode, shopName, buyerName, buyerOId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_order');

    if (name != "" && name != undefined && name != null) {
        query.equalTo("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (receiver != "" && receiver != undefined && receiver != null) {
        query.contains("receiver", receiver);
    }
    if (orderCode != "" && orderCode != undefined && orderCode != null) {
        query.equalTo("orderCode", Number(orderCode));
    }

    if (shopName != "" && shopName != undefined && shopName != null) {
        function find(shopUser) {
            var User = new AV.Query('Shop_shop');
            User.contains('name', shopUser);
            var seller = User.find().then(function (resullt) {
                var sellerArr = [];
                for (var i = 0; i < resullt.length; i++) {
                    var sellerQuery = resullt[i].get("objectId");
                    sellerArr.push(sellerQuery);
                }
                return query.containedIn("shopOId", sellerArr);
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
            return seller;
        }

        await find(shopName);
    }
    if (buyerName != "" && buyerName != undefined && buyerName != null) {
        function findBuyer(buyerUser) {
            var User = new AV.Query('_User');
            User.contains('nickName', buyerUser);
            var buyer = User.find().then(function (result) {
                var buyerArr = [];
                for (var i = 0; i < result.length; i++) {
                    var buyerQuery = result[i].get("objectId");
                    buyerArr.push(buyerQuery);
                }
                return query.containedIn("buyerOId", buyerArr);
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
            return buyer;
        }

        await findBuyer(buyerName);
    }
    if (buyerOId != "" && buyerOId != undefined && buyerOId != null) {
        query.equalTo("buyerOId", buyerOId);
    }

    if (status != "" && status != undefined && status != null && status != "10") {
        if (status != "4") {
            query.equalTo("status", Number(status));
        } else {
            query.greaterThanOrEqualTo("status", Number(status));
        }
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('payInfo');
    query.include('shopObj');
    query.include('buyerObj');
    query.include('sellerObj');
    query.include('fightGroupObj');
    query.include('orderGoodsArray');
    query.descending('createdAt');
    query.find().then(function (result) {

            query.count().then(async function (count) {
                var obj = {};
                var start = async function () {
                    var data = [];
                    for (var i = 0; i < result.length; i++) {
                        var goodsObj = await sleep(result[i]);
                        data.push(goodsObj)
                    }
                    return data;
                };

                function sleep(order) {
                    var goods = new AV.Query('Shop_order_goods');
                    goods.equalTo("orderOId", order.id);
                    var goodsInfor = goods.first().then(async function (goods) {
                        //物流信息
                        var temObj = {};
                        temObj["objectId"] = order.id;
                        temObj["orderCode"] = order.get("orderCode");
                        temObj["receiver"] = order.get("receiver");
                        temObj["status"] = order.get("status");
                        temObj["createdAt"] = moment(order.createdAt).format('YYYY-MM-DD HH:mm:ss');
                        temObj["payTime"] = order.get("payTime");
                        temObj["totalPrice"] = order.get("totalPrice");
                        temObj["phone"] = order.get("phone");
                        temObj["payType"] = order.get("payType");
                        temObj["address"] = order.get("address");
                        temObj["expressCode"] = order.get("expressCode");
                        temObj["logisticsCom"] = order.get("logisticsCom");
                        temObj["deliverTime"] = order.get("deliverTime");
                        temObj["sellerOId"] = order.get("sellerOId");
                        temObj["shopName"] = order.get("shopObj") ? order.get("shopObj").get("name") : '';
                        temObj["shopUserName"] = order.get("sellerObj") ? order.get("sellerObj").get("nickName") : '';
                        temObj["buyerId"] = order.get("buyerObj") ? order.get("buyerObj").id : '';
                        temObj["buyerName"] = order.get("buyerObj") ? order.get("buyerObj").get("nickName") : '';
                        temObj["goodsOId"] = {};
                        let incomMoney = await whereMoneyAdd(temObj["orderCode"]) + order.get("fare");
                        let totalPrice = order.get("totalPrice");
                        incomMoney = Math.round(incomMoney * 100);
                        totalPrice = Math.round(totalPrice * 100);
                        if (incomMoney == totalPrice || temObj["status"] == 1) {
                            temObj["moneyStatus"] = 1;
                        } else {
                            temObj["moneyStatus"] = 0;
                        }
                        if (order.get("fightGroupObj") != undefined) {
                            temObj["goodsOId"]["status"] = "group"
                            temObj["goodsOId"]["objectId"] = order.get("fightGroupObj").get("objectId");
                        }
                        if (goods != '' && goods != undefined && goods != null) {
                            temObj["goodsPicURL"] = goods.get("goodsPicURL") ? goods.get("goodsPicURL") : "";
                            temObj["num"] = goods.get("num");
                            temObj["goodsOriginPrice"] = goods.get("goodsOriginPrice");
                            temObj["goodsModel"] = goods.get("goodsModel");
                            temObj["goodsName"] = goods.get("goodsName");
                            temObj["price"] = goods.get("price");
                            if (order.get("fightGroupObj") == undefined) {
                                temObj["goodsOId"]["status"] = "app"
                                temObj["goodsOId"]["objectId"] = goods.get("goodsOId");
                            }
                            temObj["groupPrice"] = goods.get("groupPrice");
                        }
                        return temObj
                    }).catch(function (err) {
                        console.log(err)
                    });
                    return goodsInfor;
                }

                function whereMoneyAdd(orderNo) {
                    let moneyQuery = new AV.Query("Shop_account_detail");
                    moneyQuery.equalTo("orderNo", Number(orderNo));
                    let MoneyQuery = moneyQuery.find().then((result) => {
                        let money = 0;
                        for (let i = 0; i < result.length; i++) {
                            money = money + Number(result[i].get("changeMoney"));
                        }
                        return money;
                    })
                    return MoneyQuery;
                }
                var resultArr = await start();
                obj.data = resultArr;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            console.log("aaaa")
        }
    )
};

exports.shopOrderList2 = shopOrderList2;

async function shopOrderList2(objectId, name, status, receiver, orderCode, shopOId, buyerName, buyerOId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_order');

    if (name != "" && name != undefined && name != null) {
        query.equalTo("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (receiver != "" && receiver != undefined && receiver != null) {
        query.contains("receiver", receiver);
    }
    if (orderCode != "" && orderCode != undefined && orderCode != null) {
        query.equalTo("orderCode", Number(orderCode));
    }
    if (shopOId != "" && shopOId) {
        query.equalTo("shopOId", shopOId);
    }

    if (buyerName != "" && buyerName != undefined && buyerName != null) {
        function findBuyer(buyerUser) {
            var User = new AV.Query('_User');
            User.contains('nickName', buyerUser);
            var buyer = User.find().then(function (result) {
                var buyerArr = [];
                for (var i = 0; i < result.length; i++) {
                    var buyerQuery = result[i].get("objectId");
                    buyerArr.push(buyerQuery);
                }
                return query.containedIn("buyerOId", buyerArr);
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
            return buyer;
        }

        await findBuyer(buyerName);
    }
    if (buyerOId != "" && buyerOId != undefined && buyerOId != null) {
        query.equalTo("buyerOId", buyerOId);
    }

    if (status != "" && status != undefined && status != null && status != "10") {
        if (status != "4") {
            query.equalTo("status", Number(status));
        } else {
            query.greaterThanOrEqualTo("status", Number(status));
        }
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('payInfo');
    query.include('shopObj');
    query.include('buyerObj');
    query.include('sellerObj');
    query.include('fightGroupObj');
    query.include('orderGoodsArray');
    query.descending('createdAt');
    query.find().then(function (result) {

            query.count().then(async function (count) {
                var obj = {};
                var start = async function () {
                    var data = [];
                    for (var i = 0; i < result.length; i++) {
                        var goodsObj = await sleep(result[i]);
                        data.push(goodsObj)
                    }
                    return data;
                };

                function sleep(order) {
                    var goods = new AV.Query('Shop_order_goods');
                    goods.equalTo("orderOId", order.id);
                    var goodsInfor = goods.first().then(async function (goods) {
                        //物流信息
                        var temObj = {};
                        temObj["objectId"] = order.id;
                        temObj["orderCode"] = order.get("orderCode");
                        temObj["receiver"] = order.get("receiver");
                        temObj["status"] = order.get("status");
                        temObj["createdAt"] = moment(order.createdAt).format('YYYY-MM-DD HH:mm:ss');
                        temObj["payTime"] = order.get("payTime");
                        temObj["totalPrice"] = order.get("totalPrice");
                        temObj["phone"] = order.get("phone");
                        temObj["payType"] = order.get("payType");
                        temObj["address"] = order.get("address");
                        temObj["expressCode"] = order.get("expressCode");
                        temObj["logisticsCom"] = order.get("logisticsCom");
                        temObj["deliverTime"] = order.get("deliverTime");
                        temObj["sellerOId"] = order.get("sellerOId");
                        temObj["shopName"] = order.get("shopObj") ? order.get("shopObj").get("name") : '';
                        temObj["shopUserName"] = order.get("sellerObj") ? order.get("sellerObj").get("nickName") : '';
                        temObj["buyerId"] = order.get("buyerObj") ? order.get("buyerObj").id : '';
                        temObj["buyerName"] = order.get("buyerObj") ? order.get("buyerObj").get("nickName") : '';
                        temObj["goodsOId"] = {};
                        let incomMoney = await whereMoneyAdd(temObj["orderCode"]) + order.get("fare");
                        let totalPrice = order.get("totalPrice");
                        incomMoney = Math.round(incomMoney * 100);
                        totalPrice = Math.round(totalPrice * 100);
                        if (incomMoney == totalPrice || temObj["status"] == 1) {
                            temObj["moneyStatus"] = 1;
                        } else {
                            temObj["moneyStatus"] = 0;
                        }
                        if (order.get("fightGroupObj") != undefined) {
                            temObj["goodsOId"]["status"] = "group"
                            temObj["goodsOId"]["objectId"] = order.get("fightGroupObj").get("objectId");
                        }
                        if (goods != '' && goods != undefined && goods != null) {
                            temObj["goodsPicURL"] = goods.get("goodsPicURL") ? goods.get("goodsPicURL") : "";
                            temObj["num"] = goods.get("num");
                            temObj["goodsOriginPrice"] = goods.get("goodsOriginPrice");
                            temObj["goodsModel"] = goods.get("goodsModel");
                            temObj["goodsName"] = goods.get("goodsName");
                            temObj["price"] = goods.get("price");
                            if (order.get("fightGroupObj") == undefined) {
                                temObj["goodsOId"]["status"] = "app"
                                temObj["goodsOId"]["objectId"] = goods.get("goodsOId");
                            }
                            temObj["groupPrice"] = goods.get("groupPrice");
                        }
                        return temObj
                    }).catch(function (err) {
                        console.log(err)
                    });
                    return goodsInfor;
                }

                function whereMoneyAdd(orderNo) {
                    let moneyQuery = new AV.Query("Shop_account_detail");
                    moneyQuery.equalTo("orderNo", Number(orderNo));
                    let MoneyQuery = moneyQuery.find().then((result) => {
                        let money = 0;
                        for (let i = 0; i < result.length; i++) {
                            money = money + Number(result[i].get("changeMoney"));
                        }
                        return money;
                    })
                    return MoneyQuery;
                }
                var resultArr = await start();
                obj.data = resultArr;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            console.log(error)
            console.log("aaaa")
        }
    )
};
exports.updataOrder = updataOrder;

function updataOrder(req, callback) {
    var objectId = req.params.objectId;
    // 修改属性
    var User = AV.Object.createWithoutData('Shop_order', objectId);
    User.set('receiver', req.params.receiver);
    User.set('address', req.params.address);
    // 保存到云端
    User.save().then(function (success) {
            callback(success);
        }, function (error) {
            console.log(error);
        }
    )
}

exports.updataOrderStatus = updataOrderStatus;

function updataOrderStatus(req, callback) {
    var objectId = req.params.objectId;
    // 修改属性
    var User = AV.Object.createWithoutData('Shop_order', objectId);
    User.set('receiver', req.params.receiver);
    User.set('address', req.params.address);
    User.set('status', Number(req.params.status));
    // 保存到云端
    User.save().then(function (success) {
            callback("null", success);
        }, function (error) {
            console.log(error);
        }
    )
}

exports.shopOrderRefund = shopOrderRefund;

function shopOrderRefund(objectId, callback) {
    var query = new AV.Query('Shop_order');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.include('orderRefundObj');
    query.include('shopObj');
    query.include('buyerObj');
    query.descending('createdAt');
    query.first().then(function (result) {
            var obj = {};
            var data = [];
            var temObj = {};
            temObj['refundId'] = result.get('orderRefundObj').get('objectId');
            temObj['refundFee'] = result.get('orderRefundObj').get('refundFee');
            temObj['refundAnswer'] = result.get('orderRefundObj').get('refundAnswer') ? result[i].get('orderRefundObj').get('refundAnswer') : "";
            temObj['type'] = result.get('orderRefundObj').get('type');
            temObj['title'] = result.get('orderRefundObj').get('title');
            temObj["orderCode"] = result.get("orderCode");
            temObj['refundReason'] = result.get('orderRefundObj').get('refundReason');
            temObj['createdAt'] = moment(result.createdAt).format('YYYY-MM-DD HH:mm:ss');
            data.push(temObj)
            obj.data = data;
            callback("null", obj);
        }, function (error) {
            console.log("aaaa")
        }
    )
}

// 发货
exports.doSendGoods = doSendGoods;

function doSendGoods(request, callback) {
    var orderOId = request.params.orderOId;
    var logisticsComCode = request.params.logisticsComCode;//快递公司代码
    var logisticsCom = request.params.logisticsCom;//物流公司
    var expressCode = request.params.expressCode;//快递编号
    var sellerOId = request.params.sellerOId;
    var orderQuery = new AV.Query("Shop_order");
    if(sellerOId&&sellerOId!=""){
        orderQuery.equalTo("sellerOId", sellerOId);
    }
    orderQuery.equalTo("objectId", orderOId);
    orderQuery.include("buyerObj");
    var statusArry = [apis["order"]["status_noSend"], apis["order"]["status_noReceive"]];
    orderQuery.containedIn("status", statusArry);
    orderQuery.first(
    ).then(function (orderObj) {
            if (orderObj == null) {
                return callback(null, 10001);
            } else {
                orderObj.set("logisticsComCode", logisticsComCode);
                if (logisticsComCode == "-1") {
                    logisticsCom = "无需物流";
                    expressCode = "";
                }
                orderObj.set("logisticsCom", logisticsCom);
                orderObj.set("expressCode", expressCode);
                orderObj.set("logisticsTime", new Date());
                orderObj.set("logisticsData", '');
                orderObj.set("deliverTime", new Date());
                if (orderObj.get("orderSendCount") == "" || orderObj.get("orderSendCount") == null || orderObj.get("orderSendCount") == undefined) {
                    orderObj.set("orderSendCount", 1);
                } else {
                    orderObj.increment("orderSendCount", 1);
                }
                orderObj.set("oldStatus", orderObj.get("status"));
                orderObj.set("status", apis['order']['status_noReceive']);
                orderObj.set("task", apis["taskType"]["orderReceive"]);//定时任务
                orderObj.set("taskTime", new Date(moment().add(apis["taskType"]["orderReceiveDate"], 'days')));//定时任务时间
                orderObj.save().then(function (orderObj) {
                        // 发货通知
                        sendOrderTip([orderObj], function (error, result) {
                        });
                        return callback(null, 10000);
                    }, function (errObj, error) {
                        return callback(null, 10001);
                    }
                );
            }
        },
        function (error) {
            return callback(null, 10002);
        });
}

exports.sendOrderTip = sendOrderTip;

function sendOrderTip(orders, callback) {
    var orderObj = null;
    for (var i = 0; i < orders.length; i++) {
        orderObj = orders[i];
        var logisticsComCode = orderObj.get("logisticsComCode");//快递公司代码
        var logisticsCom = orderObj.get("logisticsCom");//快递公司
        var expressCode = orderObj.get("expressCode");//物流号
        var content = "亲，您购买的订单号为" + orderObj.get('orderCode') + "的 " + orderObj.get('goods').join('、') + " 产品掌柜已发货";
        var msmContent = "";
        if (logisticsComCode == "-1") {
            msmContent += "发货方式是：无需物流";
        } else {
            msmContent += "快递公司是：" + logisticsCom + "，快递号是：" + expressCode;
        }
        msmContent += "，请注意查收！";
        content += "," + msmContent;
        var toUserOId = orderObj.get("buyerOId");

        // 推送交易消息
        var msg_content = {};
        msg_content["content"] = content;

        var msg_extra = {};
        msg_extra["extra"] = apis['message_profession_code']['transaction_code']; //交易消息代码
        msg_extra["code"] = apis['message_type_code']['word']; //文本消息
        msg_extra["content"] = msg_content;

        var base64Content = new Buffer(JSON.stringify(msg_extra)).toString('base64');
        base64Content = base64Content.replace(/\+/g, "@");
        base64Content = base64Content.replace(/\=/g, "");

        var sendObj = {};
        sendObj["operation"] = "";
        sendObj["sourceUserId"] = "";
        sendObj["targetUserId"] = "";
        sendObj["extra"] = base64Content;
        message.publish("admin", toUserOId, "RC:ContactNtf", JSON.stringify(sendObj), "json", function (err, result1) {
        });

        //记录到系统消息中
        var SystemMessage = common.getEntity('SystemMessage');
        var systemMessage = new SystemMessage();
        systemMessage.set('targetUserOId', toUserOId);
        systemMessage.set('targetUserObj', {"__type": "Pointer", className: "_User", objectId: toUserOId});
        systemMessage.set('sortTime', common.getCurrTime());
        systemMessage.set('status', 0);
        systemMessage.set('messageType', 2);
        systemMessage.set('isBuyer', 1);
        systemMessage.set('orderObj', orderObj);
        systemMessage.set('title', '卖家已发货');
        systemMessage.set('content', msg_content['content']);
        systemMessage.save();

        //短信通知
        if (orderObj.get("buyerObj") != null && orderObj.get("buyerObj") != undefined) {
            var tel = orderObj.get("buyerObj").get("mobilePhoneNumber");
            if (tel != null && tel != undefined && tel != "") {
                AV.Cloud.requestSmsCode({
                    mobilePhoneNumber: tel,
                    deliverTip: msmContent,
                    orderNo: orderObj.get("orderCode"),
                    goods: orderObj.get('goods').join('、'),
                    template: 'delive_msg'
                }).then(function () {
                }, function (err) {
                });
            }
        }
    }
    return callback(null, null);
}

//tribeLiveList
exports.tribeLiveList = tribeLiveList;

async function tribeLiveList(objectId, tribeOId, qiniuStreamId, createrOId, nickName, page, num) {
    console.log(page, "page======")
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Tribe_live');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        query.equalTo("tribeOId", tribeOId);
    }
    if (qiniuStreamId != "" && qiniuStreamId != undefined && qiniuStreamId != null) {
        let liveRoom = new AV.Query('Live_room');
        liveRoom.equalTo("qiniuStreamId", qiniuStreamId);
        query.matchesQuery('liveObj', liveRoom);
    }
    if (createrOId != "" && createrOId != undefined && createrOId != null) {

        let liveRoom = new AV.Query('Live_room');
        liveRoom.equalTo("createrOId", createrOId);
        query.matchesQuery('liveObj', liveRoom);
    }
    // if (nickName != "" && nickName != undefined && nickName != null) {
    //
    //        function findNickName(createName) {
    //           let User = new AV.Query('_User');
    //           User.contains('nickName', createName);
    //           let liveRoom = new AV.Query('Live_room');
    //           liveRoom.matchesQuery("createrObj",User);
    //           return liveRoom.find().then(function (result) {
    //               for (let item of result) {
    //                   let buyerQuery = item.get("objectId");
    //                   buyerArr.push(buyerQuery);
    //               }
    //               return query.containedIn("liveOId", buyerArr);
    //           },function (reject) {
    //               return reject
    //           }).catch(error=>{
    //               return error
    //           })
    //        }
    //   await findNickName(nickName);
    // }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include("liveObj");
    query.include("tribeObj");
    query.include("liveObj.createrObj");
    query.descending('createdAt');
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let itemObj = {};
                let liveObj = item.get("liveObj");
                itemObj["objectId"] = liveObj ? liveObj.get("objectId") : "";
                itemObj["qiniuStreamId"] = liveObj ? liveObj.get("qiniuStreamId") : "";//直播流ID
                itemObj["isRecord"] = liveObj ? liveObj.get("isRecord") : "";
                itemObj["title"] = liveObj ? liveObj.get("title") : "";
                itemObj["nickName"] = liveObj ? (liveObj.get("createrObj") ? liveObj.get("createrObj").get("nickName") : "") : "";
                itemObj["userAvatar"] = liveObj ? (liveObj.get("createrObj").get("userAvatar") ? liveObj.get("createrObj").get("userAvatar").url() : "") : "";
                itemObj["tribeName"] = item.get("tribeObj") ? item.get("tribeObj").get("name") : "";
                itemObj["createrOId"] = liveObj ? liveObj.get("createrOId") : "";
                itemObj["tribeOId"] = liveObj ? liveObj.get("tribeOId") : "";
                itemObj["streambackup"] = liveObj ? liveObj.get("streambackup") : "";
                itemObj["firstLevel"] = liveObj ? liveObj.get("firstLevel") : "";
                itemObj["lastLevel"] = liveObj ? liveObj.get("lastLevel") : "";
                let startTime = liveObj ? liveObj.get("playTime") : "";//开始时间
                let endTime = liveObj ? liveObj.get("endTime") : "";//结束时间
                itemObj["playTime"] = Math.round((Date.parse(endTime) - Date.parse(startTime)) / 60 / 1000)//直播时间
                itemObj["status"] = liveObj ? liveObj.get("status") : "";//-1删除 0禁播 1预约 2 中 3结束 4录播
                itemObj["createdAt"] = liveObj ? moment(liveObj.createdAt).format('YYYY-MM-DD HH:mm:ss') : "";
                itemObj["startTime"] = moment(startTime).format('YYYY年MM月DD HH:mm:ss');
                itemObj["endTime"] = moment(endTime).format('YYYY年MM月DD HH:mm:ss');
                data.push(itemObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    }).catch(error => {
        console.log(error);
        return null;
    })
}

// 直播信息
exports.liveList = liveList;

async function liveList(objectId, tribeOId, qiniuStreamId, createrOId, nickName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Live_room');


    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }

    if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
        query.equalTo("tribeOId", tribeOId);
    }

    if (qiniuStreamId != "" && qiniuStreamId != undefined && qiniuStreamId != null) {
        query.equalTo("qiniuStreamId", qiniuStreamId);
    }
    if (createrOId != "" && createrOId != undefined && qiniuStreamId != null) {
        query.equalTo("createrOId", createrOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        function findCreater(createrName) {
            var User = new AV.Query('_User');
            User.contains('nickName', createrName);
            var buyer = User.find().then(function (result) {
                var buyerArr = [];
                for (var i = 0; i < result.length; i++) {
                    var buyerQuery = result[i].get("objectId");
                    buyerArr.push(buyerQuery);
                }
                return query.containedIn("createrOId", buyerArr);
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
            return buyer;
        }

        await findCreater(nickName);
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('createrObj');
    query.include('tribeObj');
    query.descending('createdAt');
    query.include("questionObj");

    query.find().then(function (result) {
            query.count().then(function (count) {
                var obj = {};
                var data = [];
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["qiniuStreamId"] = result[i].get("qiniuStreamId");//直播流Id
                    temObj["isRecord"] = result[i].get("isRecord");//1录播 2上传 0直播
                    temObj["title"] = result[i].get("title");
                    temObj["nickName"] = result[i].get("createrObj") ? result[i].get("createrObj").get("nickName") : "";
                    temObj["userAvatar"] = result[i].get("createrObj") ? (result[i].get("createrObj").get("userAvatar") ? result[i].get("createrObj").get("userAvatar").url() : '') : "";
                    temObj["rtmpUrl"] = result[i].get("rtmpUrl");
                    temObj["tribeName"] = result[i].get("tribeObj") ? result[i].get("tribeObj").get("name") : "";
                    temObj["createrOId"] = result[i].get("createrOId");
                    temObj["tribeOId"] = result[i].get("tribeOId");
                    temObj["streambackup"] = result[i].get("streambackup");
                    temObj["firstLevel"] = result[i].get("firstLevel");
                    temObj["lastLevel"] = result[i].get("lastLevel");
                    temObj["questionTitle"] = result[i].get("questionObj") ? result[i].get("questionObj").get("title") : "";
                    temObj["browseNum"] = result[i].get("browseNum");
                    var startTime = result[i].get("playTime");//开始时间
                    var endTime = result[i].get("endTime");//结束时间
                    temObj["playTime"] = Math.round((Date.parse(endTime) - Date.parse(startTime)) / 60 / 1000)//直播时间
                    temObj["status"] = result[i].get("status");//-1删除 0禁播 1预约 2 中 3结束 4录播
                    temObj["createdAt"] = moment(result[i].createdAt).format('YYYY-MM-DD HH:mm:ss');
                    temObj["startTime"] = moment(startTime).format('YYYY年MM月DD HH:mm:ss');
                    temObj["endTime"] = moment(endTime).format('YYYY年MM月DD HH:mm:ss');

                    data.push(temObj);
                }
                obj.data = data;
                obj.total = count;

                callback("null", obj);
            }).catch(err => {
                console.log(err)
            })
        }, function (error) {
            console.log(error)
        }
    )
}

//添加设备直播
exports.createLive = createLive;

function createLive(params, callback) {
    params.tribeOIds = [params.tribeOId]
    var Live_room = common.getEntity('Live_room');
    var room = new Live_room();
    var createrObj = AV.Object.createWithoutData('_User', params.createrOId);
    var tribeObj = AV.Object.createWithoutData('Tribe', params.tribeOId);
    room.set('createrOId', params.createrOId);
    room.set('createrObj', createrObj);
    room.set('coverPic', params.coverPic);
    room.set('title', params.title);
    room.set('goods', params.goods);
    // room.set('fightGroupsGoods', params.fightGroupsGoods);
    room.set('downPayment', params.downPayment);
    room.set('brokerage', params.brokerage);
    // room.set('predictTime', params.predictTime);
    // room.set('hasQuestion', params.hasQuestion);
    room.set('firstLevel', math.round(params.firstLevel, 2));
    room.set('lastLevel', math.round(params.lastLevel, 2));
    // if(1 == parseInt(params.recordLive)) {
    //   room.set('status', '4');//录播
    //   room.set("isRecord", 1);
    //   params.tribeOIds = [];
    //   params.tribeOIds.push(params.tribeOId);
    // }else{
    //   room.set("isRecord", 0);
    //   room.set('status', '2');//直播状态  2 正在直播
    // }
    //
    // if(3 == parseInt(params.recordLive)) {
    //   room.set('status', '-1');//预约直播
    //   room.set("isRecord", 3);
    // }
    room.set("isRecord", Number(params.isRecord)); //1是录播，0直播，2上传,3设备直播
    room.set('status', params.status);//直播状态  -1删除0禁播1预约2中3结束4录播
    room.set('memberNum', 1);
    room.set("browseNum", Number(params.browseNum));
    room.set('isPublic', params.isPublic);
    room.set('tribeOId', params.tribeOId);
    room.set('tribeObj', tribeObj);
    room.set('playTime', new Date());
    room.set('endTime', null);
    room.set('memberUIds', [params.createrOId]);
    // console.log('2');
    room.save().then(function (room) {
        app.createStream(room.id, function (error, streamId, createdAt, rtmpUrl) {
            if (error) {
                return callback(error, null);
            }
            // console.log(streamId,"streamId====")
            room.set('qiniuStreamId', streamId);
            room.set('rtmpUrl', rtmpUrl);
            room.set('playTime', new Date(createdAt));
            room.save();
            //直播成员表 新增记录
            var Live_Member = common.getEntity('Live_Member');
            var liveMember = new Live_Member();
            var liveObj = AV.Object.createWithoutData('Live_room', room.id);
            liveMember.set('liveOId', room.id);
            liveMember.set('liveObj', liveObj);
            liveMember.set('userOId', params.createrOId);
            liveMember.set('userObj', createrObj);
            liveMember.set('userType', '1');
            liveMember.save().then(function (liveMember) {
            }, function (error) {
                return callback(error, null);
            })
            //保存完成后 返回相关直播信息
            // console.log('3');
            room.fetch({include: 'roomNo'}, {}).then(function (room) {
                chatRoom.createRoom(room.get("roomNo"), room.get("title"), function () {
                });
                chatRoom.joinRoom(params.createrOId, room.get("roomNo"), function () {
                });
                // console.log('3333')
                //将直播关联到其他部落
                var relationLive = new AV.Query("TribeLiveRelation_background");
                relationLive.equalTo('relationTribeOId', params.tribeOId);
                relationLive.equalTo('status', 1);
                relationLive.first().then(function (relationLiveObj) {
                    if (relationLiveObj) {
                        var synchronizationLive = new AV.Query("SynchronizationLiveTribe_background");
                        synchronizationLive.equalTo('parentRelationTribeOId', params.tribeOId);
                        synchronizationLive.equalTo('status', 1);
                        synchronizationLive.limit(1000);

                        synchronizationLive.notContainedIn('tribeOId', params.tribeOIds);
                        synchronizationLive.find().then(function (synchronizationLiveObj) {
                            if (synchronizationLiveObj) {
                                for (var i = 0; i < synchronizationLiveObj.length; i++) {
                                    var LiveTribeOId = synchronizationLiveObj[i].get('tribeOId');
                                    params.tribeOIds.push(LiveTribeOId);
                                }
                            }
                            var Tribe_live = common.getEntity("Tribe_live");
                            var array = [];
                            for (var i = 0; i < params.tribeOIds.length; i++) {
                                var tribeLive = new Tribe_live();
                                tribeLive.set("liveOId", room.id);
                                tribeLive.set("liveObj", {"__type": "Pointer", "className": "Live_room", "objectId": room.id});
                                tribeLive.set("tribeOId", params.tribeOIds[i]);
                                tribeLive.set("tribeObj", {"__type": "Pointer", "className": "Tribe", "objectId": params.tribeOIds[i]});
                                tribeLive.set("status", 0);

                                if (3 == parseInt(params.recordLive)) {
                                    tribeLive.set("status", -1);
                                }
                                array.push(tribeLive);
                            }
                            // console.log('4')
                            AV.Object.saveAll(array).then(function (tribeLives) {
                                //格式化返回信息
                                // console.log('5')
                                var returnObj = {};
                                returnObj.id = room.id;
                                returnObj.streamName = room.id;
                                returnObj.coverPic = room.get('coverPic') ? apis['qiniu']['url'] + room.get('coverPic') : '';
                                returnObj.roomNo = room.get('roomNo') ? room.get('roomNo') : '';
                                console.log(returnObj)
                                return callback(null, returnObj);
                            }, function (error) {
                                console.log(error);
                                return callback(error, null);
                            });


                        })

                    } else {
                        var Tribe_live = common.getEntity("Tribe_live");
                        var array = [];
                        for (var i = 0; i < params.tribeOIds.length; i++) {
                            var tribeLive = new Tribe_live();
                            tribeLive.set("liveOId", room.id);
                            tribeLive.set("liveObj", {"__type": "Pointer", "className": "Live_room", "objectId": room.id});
                            tribeLive.set("tribeOId", params.tribeOIds[i]);
                            tribeLive.set("tribeObj", {"__type": "Pointer", "className": "Tribe", "objectId": params.tribeOIds[i]});
                            tribeLive.set("status", 0);
                            if (3 == parseInt(params.recordLive)) {
                                tribeLive.set("status", -1);
                            }

                            array.push(tribeLive);
                        }
                        AV.Object.saveAll(array).then(function (tribeLives) {
                            //格式化返回信息
                            var returnObj = {};
                            returnObj.id = room.id;
                            returnObj.streamName = room.id;
                            returnObj.coverPic = room.get('coverPic') ? apis['qiniu']['url'] + room.get('coverPic') : '';
                            returnObj.roomNo = room.get('roomNo') ? room.get('roomNo') : '';
                            return callback(null, returnObj);
                        }, function (error) {
                            console.log(error);
                            return callback(error, null);
                        });
                    }
                })
            }, function (error) {
                return callback(error, null);
            })
        });
    }, function (error) {
        return callback(error, null);
    })
}

// console.log(params)
//   var createrObj = AV.Object.createWithoutData('_User', params.createrOId);
//   var tribeObj = AV.Object.createWithoutData('Tribe', params.tribeOId);
//   var Live_room = common.getEntity('Live_room');
//   var room = new Live_room();
//   room.set('createrOId', params.createrOId);
//   room.set('createrObj', createrObj);
//   room.set('coverPic', params.coverPic);
//   room.set('title', params.title);
//   room.set('downPayment', params.downPayment);
//   room.set('brokerage', params.brokerage);
//   // if(1 == parseInt(params.recordLive)) {
//   //   room.set('status', '4');//录播
//   //   room.set("isRecord", 1);
//   // }else{
//   //   room.set('status', '2');//直播状态  2 正在直播
//   // }
//   room.set("isRecord", Number(params.isRecord)); //1是录播，0直播，2上传,3设备直播
//   room.set('status', params.status);//直播状态  -1删除0禁播1预约2中3结束4录播
//   room.set('memberNum', 1);
//   room.set('isPublic', params.isPublic);
//   room.set('tribeOId', params.tribeOId);
//   room.set('tribeObj', tribeObj);
//   room.set('playTime', new Date());
//   room.set('memberUIds', [params.createrOId]);
//   room.set("goods", []);
//   room.set('firstLevel', Number(params.firstLevel));
//   room.set('lastLevel', Number(params.lastLevel));
//   room.set("browseNum", Number(params.browseNum));
//   room.set('playTime', null);
//   room.set('endTime', null);
//   room.save().then(function(room){
//       console.log(room,'111111')
//     var liveObj = AV.Object.createWithoutData('Live_room', room.id);
//     var Tribe_live = common.getEntity("Tribe_live");
//     var tribeLive = new Tribe_live();
//     tribeLive.set("tribeOId", room.get("tribeOId"));
//     tribeLive.set("liveOId", room.id);
//     let roomTribeObj = AV.Object.createWithoutData('Tribe', room.get("tribeOId"))
//     tribeLive.set("tribeObj",roomTribeObj)
//     tribeLive.set("liveObj", liveObj);
//     tribeLive.set("status", 0);
//     tribeLive.save().then(function(tribeLive) {
//       console.log(tribeLive,'2222')
//       app.createStream(room.id,function(error, streamId,createdAt,rtmpUrl) {
//         console.log(rtmpUrl,'3333')
//         if(error) {
//           console.log(error)
//           return callback(error, null);
//         }
//         room.set('qiniuStreamId', streamId);
//         room.set('rtmpUrl',rtmpUrl);
//         room.set('playTime', new Date(createdAt));
//
//         room.save();
//         //直播成员表 新增记录
//         var Live_Member = common.getEntity('Live_Member');
//         var liveMember = new Live_Member();
//         liveMember.set('liveOId', room.id);
//         liveMember.set('liveObj', liveObj);
//         liveMember.set('userOId', params.createrOId);
//         liveMember.set('userObj', createrObj);
//         liveMember.set('userType', '1');
//         liveMember.save().then(function(liveMember){
//           console.log(liveMember,'4444')
//         },function(error){
//           console.log(error)
//           return callback(error, null);
//         })
//         //保存完成后 返回相关直播信息
//         room.fetch({include:'roomNo'},{}).then(function(room){
//           chatRoom.createRoom(room.get("roomNo"),room.get("title"),function(){});
//           chatRoom.joinRoom(params.createrOId,room.get("roomNo"),function(){});
//           console.log(room,'555')
//           //格式化返回信息
//           var returnObj = {};
//           returnObj.id = room.id;
//           returnObj.streamName = room.id;
//           returnObj.coverPic = room.get('coverPic') ? apis['qiniu']['url']+room.get('coverPic') : '';
//           returnObj.roomNo = room.get('roomNo') ? room.get('roomNo') : '';
//           console.log(returnObj,'666')
//           return callback(null, returnObj);
//         },function(error) {
//           console.log(error)
//           return callback(error, null);
//         })
//
//       });
//     },function(error) {
//         console.log(error)
//       return callback(error, null);
//     });
//   },function(error){
//     console.log(error)
//     return callback(error, null);
//   })
// }
exports.updateLive = updateLive;

function updateLive(req, callback) {
    var objectId = req.params.objectId;
    // 修改属性
    if (objectId != "" && objectId != null) {
        var Live = AV.Object.createWithoutData('Live_room', objectId);
    } else {
        var LiveObj = AV.Object.extend("Live_room")
        var Live = new LiveObj();
        var createrObj = AV.Object.createWithoutData('_User', req.params.createrOId);
        var tribeObj = AV.Object.createWithoutData('Tribe', req.params.tribeOId);
        Live.set("createrObj", createrObj)
        Live.set("tribeObj", tribeObj)
        Live.set("createrOId", req.params.createrOId)
        Live.set("tribeOId", req.params.tribeOId)
        Live.set('memberUIds', [req.params.createrOId]);
        Live.set("goods", []);
    }

    Live.set('status', req.params.status);
    Live.set('isPublic', req.params.isPublic);
    Live.set('title', req.params.title);
    Live.set('streambackup', req.params.streambackup);
    Live.set('isRecord', Number(req.params.isRecord));
    Live.set('firstLevel', Number(req.params.firstLevel));
    Live.set('lastLevel', Number(req.params.lastLevel));
    Live.set("coverPic", req.params.coverPic)
    Live.set("browseNum", Number(req.params.browseNum));
    Live.set('playTime', null);
    Live.set('endTime', null);
    // 保存到云端
    Live.save().then(function (live) {
        var Tribe_live = AV.Object.extend("Tribe_live");
        var tribeLive = new Tribe_live();
        var tribeObj = AV.Object.createWithoutData('Tribe', req.params.tribeOId);
        var liveObj = AV.Object.createWithoutData('Live_room', live.id);
        tribeLive.set("tribeOId", live.get("tribeOId"));
        tribeLive.set("liveOId", live.id);
        tribeLive.set("tribeObj", tribeObj)
        tribeLive.set("liveObj", liveObj);
        tribeLive.set("status", 0);
        tribeLive.save().then(function (tribeLive) {
            callback(null, tribeLive)
        }, function (err) {
            callback(err, null)
        })
    })
}

exports.removeLive = removeLive;

function removeLive(req, callback) {
    var objectId = req.params.objectId;
    // 修改属性
    var live = AV.Object.createWithoutData('Live_room', objectId);
    live.set('status', req.params.status);
    live.save().then(result => {
        if (result) {
            var query = new AV.Query("Tribe_live");
            query.equalTo("liveOId", objectId)
            query.find().then(tribeLives => {
                let data = []
                tribeLives.forEach(item => {
                    item.set('status', -1)
                    data.push(item)
                })
                AV.Object.saveAll(data).then(saveRes => {
                    callback(null, saveRes)
                }).catch(saveErr => {
                    console.log(saveErr)
                    callback(saveErr, null)
                })
            }).catch(err => {
                console.log(err)
                callback(err, null)
            })
        } else {
            console.log('修改直播状态失败！')
            callback('修改直播状态失败！', null)
        }
    }).catch(error => {
        console.log(error)
        callback(error, null)
    })
}

exports.updateLiveRoom = updateLiveRoom;

function updateLiveRoom(req) {
    let objectId = req.params.objectId;
// 修改属性
    let Live = AV.Object.createWithoutData('Live_room', objectId);
    Live.set('title', req.params.title);
    Live.set('firstLevel', Number(req.params.firstLevel));
    Live.set('lastLevel', Number(req.params.lastLevel));
    Live.set("browseNum", Number(req.params.browseNum));
// 保存到云端
    return Live.save().then(function (data) {
        return data
    })
}

//收益列表
exports.accountList = accountList;

async function accountList(remark, userOId, nickName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_account_detail');
    if (remark != 0 && remark != undefined && remark != null && remark != 1 && remark != 3) {
        query.equalTo("remark", remark);
    }
    if (remark == 3) {
        query.equalTo("changeType", remark);
    }
    if (remark == 1) {
        query.equalTo("refund", remark);
    }
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        function findCreater(createrName) {
            var User = new AV.Query('_User');
            User.contains('nickName', createrName);
            var buyer = User.find().then(function (result) {
                var userArr = [];
                for (var i = 0; i < result.length; i++) {
                    var buyerQuery = result[i].get("objectId");
                    userArr.push(buyerQuery);
                }
                return query.containedIn("userOId", userArr);
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
            return buyer;
        }

        await findCreater(nickName);
    }
    query.skip((page - 1) * num);
    query.limit(num);
    // query.notEqualTo('orderNo',null);
    query.include('userObj');
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(function (count) {
                var obj = {};
                var data = [];
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["remark"] = result[i].get("remark");//收益类型
                    temObj["status"] = result[i].get("status");//1正常，0冻结
                    temObj["changeMoney"] = Math.round(result[i].get("changeMoney") * 100) / 100;
                    temObj["changeType"] = result[i].get("changeType");
                    temObj["refund"] = result[i].get("refund");
                    temObj["orderNo"] = result[i].get("orderNo");
                    temObj["nickName"] = result[i].get("userObj") ? result[i].get("userObj").get("nickName") : "";
                    temObj["userAvatar"] = result[i].get("userObj") ? result[i].get("userObj").get("userAvatar") ? result[i].get("userObj").get("userAvatar").url() : "" : "";
                    temObj["userOId"] = result[i].get("userOId");
                    temObj["createdAt"] = moment(result[i].createdAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY年MM月DD HH:mm:ss');
                    data.push(temObj);
                }
                obj.data = data;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            callback(error, obj);
            console.log(error)
        }
    )
}

exports.shopOrderLog = shopOrderLog;

function shopOrderLog(objectId, callback) {
    var query = new AV.Query("Shop_order");
    query.equalTo('objectId', objectId);
    query.first().then(function (order) {
        getOrderLogistice(order, function (logObj) {
            for (var i = 0; i < logObj.data.length; i++) {
                logObj.data[i].time = moment(logObj.data[i].time).format('YYYY年MM月DD HH:mm:ss')

            }
            callback(null, logObj);
        })
    })
}

// 物流信息
exports.getOrderLogistice = getOrderLogistice

function getOrderLogistice(orderObj, callback) {
    var logisticeObj = {};
    logisticeObj["status"] = "-1";
    logisticeObj["statusVal"] = apis["logisticeStatus"][logisticeObj["state"]];
    logisticeObj["expIcon"] = "";
    logisticeObj["message"] = "";
    logisticeObj["errCode"] = "0";
    logisticeObj["data"] = [];
    logisticeObj["html"] = "";
    logisticeObj["mailNo"] = "";
    logisticeObj["expTextName"] = "";
    logisticeObj["expSpellName"] = "";
    logisticeObj["update"] = "";
    logisticeObj["cache"] = "";
    logisticeObj["ord"] = "";
    logisticeObj["tel"] = "";
    //无效订单
    if (orderObj == null || orderObj == "" || orderObj == undefined) {
        logisticeObj["message"] = "无效的订单";
        return callback(logisticeObj);
    } else {
        //是否发货
        if (orderObj.get("status") <= apis["order"]["status_noSend"] || orderObj.get("deliverTime") == null) {
            logisticeObj["message"] = "订单没有发货信息";
            return callback(logisticeObj);
        } else {
            if (orderObj.get("logisticsComCode") == "-1") {
                logisticeObj["message"] = "无需物流，" + common.formatDateNormal(orderObj.get("deliverTime"), null) + "已发货";
                return callback(logisticeObj);
            } else {
                var com = orderObj.get("logisticsComCode");//物流公司编码
                var nu = orderObj.get("expressCode");//物流单号
                logisticeObj["mailNo"] = nu;
                logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");

                //如果订单中物流信息为空
                var logisticeData = orderObj.get("logisticsData");
                if (logisticeData == "" || logisticeData == null || logisticeData == undefined) {
                    kuaidiSearch(com, nu, function (err, result) {

                        var tempResult = (result.text.replace("/**/&&", "").replace("(", "").replace(")", ""));
                        orderObj.set("logisticsTime", new Date());
                        logisticeObj = JSON.parse(tempResult);
                        logisticeObj["statusVal"] = apis["logisticeStatus"][logisticeObj["state"]];
                        logisticeObj["expIcon"] = apis["logisticeIcon"][orderObj.get("logisticsComCode")];
                        logisticeObj["errCode"] = "0";
                        logisticeObj["mailNo"] = nu;
                        logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
                        logisticeObj["orderCode"] = orderObj.get("orderCode");
                        logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
                        orderObj.set("logisticsData", JSON.stringify(logisticeObj));
                        orderObj.save();


                        return callback(logisticeObj);
                    })
                }
                else {
                    //物流信息是否是最终信息(签收或退回)，是的话直接返回
                    logisticeData = JSON.parse(logisticeData);
                    if (logisticeData.status == "3" || logisticeData.status == "4") {
                        logisticeObj = logisticeData;
                        logisticeObj["statusVal"] = apis["logisticeStatus"][logisticeObj["status"]];
                        logisticeObj["expIcon"] = apis["logisticeIcon"][orderObj.get("logisticsComCode")];
                        logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
                        logisticeObj["orderCode"] = orderObj.get("orderCode");
                        logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
                        return callback(logisticeObj);
                    }
                    //否则判断物流信息是否过期，没过期的直接返回(设置30分钟缓存时间)
                    else {
                        if (new Date().getTime() - orderObj.get("logisticsTime").getTime() < 30 * 60 * 1000) {
                            logisticeObj = logisticeData;
                            logisticeObj["statusVal"] = apis["logisticeStatus"][logisticeObj["state"]];
                            logisticeObj["expIcon"] = apis["logisticeIcon"][orderObj.get("logisticsComCode")];
                            logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
                            logisticeObj["orderCode"] = orderObj.get("orderCode");
                            logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
                            return callback(logisticeObj);
                        }
                        //过期则更新订单物流信息并返回
                        else {
                            kuaidiSearch(com, nu, function (err, result) {
                                if (err) {
                                    logisticeObj["message"] = err;
                                    return callback(logisticeObj);
                                } else {

                                    var tempResult = (result.text.replace("/**/&&", "").replace("(", "").replace(")", ""));


                                    orderObj.set("logisticsTime", new Date());


                                    logisticeObj = JSON.parse(tempResult);
                                    logisticeObj["statusVal"] = apis["logisticeStatus"][logisticeObj["state"]];
                                    logisticeObj["expIcon"] = apis["logisticeIcon"][orderObj.get("logisticsComCode")];


                                    logisticeObj["errCode"] = "0";
                                    logisticeObj["mailNo"] = nu;
                                    logisticeObj["logisticsCom"] = orderObj.get("logisticsCom");
                                    logisticeObj["orderCode"] = orderObj.get("orderCode");
                                    logisticeObj["createOrderTime"] = moment(orderObj.createdAt).format('YYYY-MM-DD HH:mm:ss');
                                    orderObj.set("logisticsData", JSON.stringify(logisticeObj));
                                    orderObj.save();


                                    return callback(logisticeObj);
                                }
                            })
                        }
                    }
                }
            }
        }
    }
};


function kuaidiSearch(com, nu, callback) {
    if (com == "kuaijie") {
        com = "kuaijiesudi";
    }

    if (com == "quanfeng") {
        com = "quanfengkuaidi";
    }

    if (com == "huitong") {
        com = "huitongkuaidi";
    }

    if (com == "debang") {
        com = "debangwuliu";
    }

    if (com == "yousu") {
        com = "youshuwuliu";
    }

    if (com == "pingyou") {
        com = "youzhengguonei";
    }

    if (com == "guotong") {
        com = "guotongkuaidi";
    }


    rongrequest.kuaidiSearch("http://m.kuaidi100.com/query", {
        type: com,
        postid: nu
    }, function (err, resultText) {
        return callback(err, resultText);
    });


}

exports.getIncomSource = getIncomSource;

function getIncomSource(userOId, objectId, callback) {
    var orderQuery = new AV.Query('Shop_account_detail');
    orderQuery.equalTo("objectId", objectId);
    orderQuery.equalTo("userOId", userOId);
    orderQuery.first().then(function (detailObj) {
        if (!detailObj) {
            return callback(null, JSON.stringify(common.getErrArr("无效的数据")));
        } else {
            var returnObj = {};
            returnObj["money"] = detailObj.get("changeMoney").toString();
            returnObj["orderNo"] = detailObj.get("orderNo");
            if (detailObj.get("withdrawStatus") != "") {
                returnObj["withdrawStatus"] = detailObj.get("withdrawStatus");
            } else {
                returnObj["withdrawStatus"] = "";
            }
            if (detailObj.get("bankName") != "") {
                returnObj["bankName"] = detailObj.get("bankName");
            } else {
                returnObj["bankName"] = "";
            }
            if (detailObj.get("bankNo") != "") {
                returnObj["bankNo"] = detailObj.get("bankNo");
            } else {
                returnObj["bankNo"] = "";
            }

            returnObj["remark"] = detailObj.get("remark");
            returnObj["createdAt"] = detailObj.createdAt.getTime();
            //查询订单详情

            if (detailObj.get("remark") == "部落收入") {
                var orderShop = {};
                orderShop["shopInfo"] = {};
                orderShop["goods"] = [];
                returnObj["orderGoods"] = orderShop;
                return callback(null, returnObj);

            }

            else if (!detailObj.get("orderNo")) {
                var orderShop = {};
                orderShop["shopInfo"] = {};
                orderShop["goods"] = [];
                returnObj["orderGoods"] = orderShop;
                return callback(null, returnObj);
            } else {
                var query = new AV.Query('Shop_order');
                query.equalTo("orderCode", detailObj.get("orderNo"));
                query.include("shopObj");
                query.include("shareGoodsObj");
                query.include("orderGoodsArray");
                query.first().then(function (orderObj) {
                    if (!orderObj) {
                        return callback(null, JSON.stringify(common.getErrArr("无效的数据")));
                    } else {
                        returnObj["orderNo"] = detailObj.get("orderNo");
                        var orderShop = {};
                        orderShop["shopInfo"] = common.getShopInfo(orderObj.get("shopObj"));
                        var orderGoodsArry = orderObj.get("orderGoodsArray");

                        var goodsArry = [];
                        var goods = null;

                        if (orderGoodsArry) {

                            if (detailObj.get("remark").indexOf("销售") > -1) {

                                for (var i = 0; i < orderGoodsArry.length; i++) {
                                    goods = {};
                                    goods["goodsPicURL"] = orderGoodsArry[i].get("goodsPicURL");
                                    goods["goodsModel"] = orderGoodsArry[i].get("goodsModel");
                                    goods["num"] = orderGoodsArry[i].get("num");
                                    goods["goodsName"] = orderGoodsArry[i].get("goodsName");
                                    goods["goodsOId"] = orderGoodsArry[i].get("goodsOId");
                                    goodsArry.push(goods);
                                }
                            } else if (detailObj.get("remark").indexOf("推广") > -1) {

                                for (var i = 0; i < orderGoodsArry.length; i++) {
                                    goods = {};
                                    if (orderGoodsArry[i].get("distributor") == uId) {
                                        goods["goodsPicURL"] = orderGoodsArry[i].get("goodsPicURL");
                                        goods["goodsModel"] = orderGoodsArry[i].get("goodsModel");
                                        goods["num"] = orderGoodsArry[i].get("num");
                                        goods["goodsName"] = orderGoodsArry[i].get("goodsName");
                                        goods["goodsOId"] = orderGoodsArry[i].get("goodsOId");
                                        goodsArry.push(goods);
                                    }
                                }
                            } else if (detailObj.get("remark").indexOf("佣金") > -1) {

                                for (var i = 0; i < orderGoodsArry.length; i++) {
                                    goods = {};
                                    if (orderGoodsArry[i].get("promoter") == uId) {
                                        goods["goodsPicURL"] = orderGoodsArry[i].get("goodsPicURL");
                                        goods["goodsModel"] = orderGoodsArry[i].get("goodsModel");
                                        goods["num"] = orderGoodsArry[i].get("num");
                                        goods["goodsName"] = orderGoodsArry[i].get("goodsName");
                                        goods["goodsOId"] = orderGoodsArry[i].get("goodsOId");
                                        goodsArry.push(goods);
                                    }
                                }
                            } else if (detailObj.get("remark").indexOf("写手") > -1) {

                                for (var i = 0; i < orderGoodsArry.length; i++) {
                                    goods = {};
                                    if (orderGoodsArry[i].get("writer") == uId) {
                                        goods["goodsPicURL"] = orderGoodsArry[i].get("goodsPicURL");
                                        goods["goodsModel"] = orderGoodsArry[i].get("goodsModel");
                                        goods["num"] = orderGoodsArry[i].get("num");
                                        goods["goodsName"] = orderGoodsArry[i].get("goodsName");
                                        goods["goodsOId"] = orderGoodsArry[i].get("goodsOId");
                                        goodsArry.push(goods);
                                    }
                                }
                            }
                        }
                        orderShop["shareGoods"] = common.getShareGoods(orderObj.get("shareGoodsObj"));
                        orderShop["goods"] = goodsArry;
                        returnObj["orderGoods"] = orderShop;
                        return callback(null, JSON.stringify(returnArr));
                        ;
                    }
                });
            }
        }
    });
}

exports.getIncomeDetail = getIncomeDetail;

function getIncomeDetail(userOId, objectId, type, callback) {

    var query = new AV.Query('Shop_account_detail');
    query.equalTo("objectId", objectId);
    query.first().then(function (orderDetailObj) {
        if (orderDetailObj != null && orderDetailObj != undefined && orderDetailObj != "") {
            var accountDetail = common.getShopAccountDetailInfo(orderDetailObj);
            var orderNo = orderDetailObj.get("orderNo");
            getIncomesource(orderNo, type, function (state, returnArr) {
                if (state != null) {
                    getTribeIncome(orderNo, function (error, returnArr) {
                        if (error) {
                            getLiveShareIncome(orderNo, accountDetail["changeMoney"], function (error, returnArr) {
                                if (error) {
                                    return callback(null, JSON.stringify("无效的数据"));
                                } else {
                                    returnArr.accountDetail = accountDetail;
                                    return callback(null, JSON.stringify(common.getReturnArr("1", "1000", "", returnArr)));
                                }
                            })
                        } else {
                            returnArr.accountDetail = accountDetail;
                            return callback(null, JSON.stringify(common.getReturnArr("1", "1000", "", returnArr)));
                        }
                    })
                } else {

                    returnArr["accountDetail"] = accountDetail

                    return callback(null, JSON.stringify(common.getReturnArr("1", "1000", "", returnArr)));
                }
            });
        } else {
            return callback(null, JSON.stringify("错误的数据"));
        }

    });
}

//获取收益的来源
function getIncomesource(orderNo, type, callback) {

    var query = new AV.Query('Shop_order');
    query.equalTo("orderCode", orderNo);
    query.include("buyerObj");
    query.include("shareGoodsObj");
    query.include("orderGoodsArray");
    query.first().then(function (orderObj) {
        if (orderObj != null && orderObj != undefined && orderObj != "" && orderObj.get("orderGoodsArray") != null && orderObj.get("orderGoodsArray") != undefined) {
            var returnArr = {};
            var buyerObj = orderObj.get("buyerObj");

            var tradeSource = {}; //交易来源
            tradeSource.buyerOId = buyerObj ? buyerObj.id : "";
            tradeSource.nickName = buyerObj && buyerObj.get("nickName") ? buyerObj.get("nickName") : "";
            tradeSource.userAvatar = buyerObj && buyerObj.get("userAvatar") ? buyerObj.get("userAvatar").url() : "";
            tradeSource.signature = buyerObj && buyerObj.get("signature") ? buyerObj.get("signature") : "";
            tradeSource.tribeName = "";
            tradeSource.tribeId = "";
            tradeSource.price = orderObj.get("sellerFee");
            tradeSource.orderNo = orderNo;
            tradeSource.orderTime = orderObj.createdAt.getTime();
            var shareGoodsObj = common.getShareGoods(orderObj.get("shareGoodsObj"));
            var orderGoods = common.getOrderGoods(orderObj.get("orderGoodsArray")[0]);

            returnArr["orderGoodsInfo"] = orderGoods;
            returnArr["shareGoodsInfo"] = shareGoodsObj;
            returnArr.tradeSource = tradeSource;

            var tribeOid = orderObj.get("orderGoodsArray")[0].get('tribeOId')
            if (tribeOid == null || tribeOid == undefined)
                tribeOid = ''
            returnArr['tribeId'] = tribeOid;
            returnArr['num'] = orderGoods['num'];
            returnArr['price'] = orderGoods['price'];
            return callback(null, returnArr);

        } else {
            return callback(1, "错误的参数");
        }
    });
}

function getTribeIncome(orderNo, callback) {
    var query = new AV.Query("Tribe_order");
    query.equalTo("orderCode", orderNo);
    query.include("tribeObj");
    query.first().then(function (tribeOrder) {
        if (tribeOrder) {
            var query = new AV.Query("VetifyTribeMember");
            query.include("userObj");
            query.equalTo("tribeOrderOId", tribeOrder.id);
            query.first().then(function (result) {
                var returnArr = {};
                var orderGoods = {};
                var tradeSource = {}; //交易来源
                var tribe = tribeOrder.get("tribeObj");
                if (result) {

                    var userObj = result.get("userObj");
                    if (userObj != undefined) {
                        tradeSource.buyerOId = userObj.id;
                        tradeSource.nickName = userObj.get("nickName") ? userObj.get("nickName") : "";
                        tradeSource.userAvatar = userObj.get("userAvatar") ? userObj.get("userAvatar").url() : "";
                        tradeSource.orderTime = result.createdAt.getTime();
                    }
                } else {
                    tradeSource.buyerOId = "";
                    tradeSource.nickName = "";
                    tradeSource.userAvatar = "";
                    tradeSource.orderTime = new Date().getTime();

                }
                orderGoods.goodsName = tribe.get("name");
                orderGoods.goodsPicURL = JSON.parse(JSON.stringify(tribe.get("tribeAvator").url()));
                orderGoods.price = tribeOrder.get("cost");
                tradeSource.tribeName = tribe.get("name") ? tribe.get("name") : "";
                tradeSource.tribeId = tribe.id;
                tradeSource.price = tribeOrder.get("cost");
                tradeSource.orderNo = orderNo;
                //tradeSource.orderTime = result.createdAt.getTime();
                returnArr.orderGoodsInfo = orderGoods;
                returnArr.tradeSource = tradeSource;
                return callback(null, returnArr);
            }, function (error) {
                return callback(null, JSON.stringify(common.getErrArr(err)));
            })
        } else {
            return callback(1, "错误的参数");
        }
    }, function (error) {
        return callback(null, JSON.stringify(common.getErrArr(err)));
    });
}

function getLiveShareIncome(orderNo, cost, callback) {
    var query = new AV.Query("Live_share_order");
    query.equalTo("orderCode", orderNo);
    query.include("liveObj");
    query.include("liveObj.tribeObj");
    query.include("userObj");
    query.first().then(async function (liveOrder) {
        if (liveOrder) {
            var returnArr = {};
            var orderGoods = {};
            var live = liveOrder.get("liveObj");
            orderGoods.goodsName = live.get("title");
            orderGoods.goodsPicURL = apis.qiniu.url + live.get("coverPic");
            orderGoods.price = cost;
            orderGoods.tribe = common.getTribeInfo(live.get("tribeObj"));
            orderGoods.liveId = live.id;
            orderGoods.playTime = live.get("playTime");
            var buyerObj = (liveOrder.get("userObj"));

            var shareUser = {};//分享用户
            var userOId = liveOrder.get("shareUsers").split(",");
            if (userOId != "" && userOId != null) {
                shareUser.data = await findUserInfo(userOId);
                shareUser.count = userOId.length;
            }

            var tradeSource = {}; //交易来源
            tradeSource.buyerOId = buyerObj.id;
            tradeSource.nickName = buyerObj.get("nickName") ? buyerObj.get("nickName") : "";
            tradeSource.userAvatar = buyerObj.get("userAvatar") ? buyerObj.get("userAvatar").url() : "";
            tradeSource.signature = buyerObj.get("signature") ? buyerObj.get("signature") : "";
            tradeSource.tribeName = "";
            tradeSource.tribeId = "";
            tradeSource.price = liveOrder.get("cost");
            tradeSource.orderNo = liveOrder.get("orderCode");
            tradeSource.orderTime = liveOrder.createdAt.getTime();


            returnArr.tradeSource = tradeSource;
            returnArr.shareUser = shareUser;
            returnArr["orderGoodsInfo"] = orderGoods;
            return callback(null, returnArr);
        } else {
            return callback(1, "错误的参数");
        }
    }, function (error) {
        return callback(null, JSON.stringify(common.getErrArr(err)));
    });
}

//店铺审核后更改商品状态
function changeGoodsStatus(sellerOId, callback) {
    var query = new AV.Query("Shop_goods");
    query.equalTo("sellerOId", sellerOId)
    query.limit(1000);
    query.find().then(function (goods) {
        goods.forEach(function (good) {
            good.set('status', 1);
        });
        return AV.Object.saveAll(goods);
    }).then(function (goods) {
        callback(null, goods)
    }, function (reject) {
        console.log("商品状态更改失败");
    })
}

//创建部落权限用户
exports.allowCreateTribeList = allowCreateTribeList;

async function allowCreateTribeList(userOId, nickName, page, num, callback) {

    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Allow_Create_Tribe');

    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        let Users = await findUser(nickName);
        query.containedIn("userOId", Users)
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt")
    query.include("userObj");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                temObj["objectId"] = result[i].get("objectId");
                temObj["userOId"] = result[i].get("userOId");
                temObj["sex"] = result[i].get("userObj") ? result[i].get("userObj").get("sex") : "";
                temObj["uid"] = result[i].get("userObj") ? result[i].get("userObj").get("uid") : "";
                temObj["username"] = result[i].get("userObj") ? result[i].get("userObj").get("username") : "";
                temObj["regisFrom"] = result[i].get("userObj") ? result[i].get("userObj").get("regisFrom") : "";
                temObj["gender"] = result[i].get("userObj") ? (result[i].get("userObj").get("userAvatar") ? result[i].get("userObj").get("userAvatar").url() : "") : "";
                temObj["mobilePhoneNumber"] = result[i].get("userObj") ? result[i].get("userObj").get("mobilePhoneNumber") : "";
                temObj["live_authority"] = result[i].get("userObj") ? result[i].get("userObj").get("live_authority") : "";
                temObj["verify_authority"] = result[i].get("userObj") ? result[i].get("userObj").get("verify_authority") : "";
                temObj["createAt"] = moment(result[i].createdAt).format('YYYY-MM-DD HH:mm:ss');
                temObj["nickName"] = result[i].get("userObj") ? result[i].get("userObj").get("nickName") : "";
                temObj["phoneRegVerify"] = result[i].get("userObj") ? result[i].get("userObj").get("phoneRegVerify") : "";
                temObj["status"] = result[i].get("userObj") ? result[i].get("userObj").get("status") : "";
                temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY-MM-DD HH:mm:ss');
                temObj["address"] = result[i].get("userObj") ? result[i].get("userObj").get("province") + result[i].get("userObj").get("city") : "";
                temObj["province"] = result[i].get("userObj") ? result[i].get("userObj").get("province") : "";
                temObj["city"] = result[i].get("userObj") ? result[i].get("userObj").get("city") : "";
                temObj["qrCode"] = result[i].get("userObj") ? (result[i].get("userObj").get("qrCode") ? result[i].get("userObj").get("qrCode").url() : "") : "";
                temObj["userType"] = result[i].get("userObj") ? result[i].get("userObj").get("userType") : "";
                temObj["signature"] = result[i].get("userObj") ? result[i].get("userObj").get("signature") : "";
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        }, function (error) {
            console.log(error);
            callback(error, null);
        })
    })
}

//创建部落授权
exports.allowCreateTribeUser = allowCreateTribeUser;

function allowCreateTribeUser(userOId, status, callback) {
    var userObj = AV.Object.createWithoutData('_User', userOId);
    var query = new AV.Query("Allow_Create_Tribe");
    query.equalTo("userOId", userOId)
    query.count().then(function (num) {
        if (num == 0) {
            var Users = AV.Object.extend('Allow_Create_Tribe');
            var User = new Users;
            User.set("userObj", userObj);
            User.set("userOId", userOId);
            User.set("status", Number(status));
            User.save().then(function (success) {
                callback(null, success)
            }, function (reject) {
                callback(reject, null)
            })
        } else {
            callback(null, "2");
        }
    })
}

exports.moneyWhereDetail = moneyWhereDetail;

function moneyWhereDetail(orderNo, callback) {
    let query = new AV.Query("Shop_account_detail");
    query.equalTo("orderNo", Number(orderNo));
    query.include("userObj");
    query.find().then((result) => {
        let obj = {};
        let data = [];
        for (let i = 0; i < result.length; i++) {
            let temObj = {};
            temObj["userOId"] = result[i].get("userOId");
            temObj["remark"] = result[i].get("remark");
            temObj["changeMoney"] = result[i].get("changeMoney");
            temObj["nickName"] = result[i].get("userObj") ? result[i].get("userObj").get("nickName") : "";
            data.push(temObj)
        }
        obj.data = data;
        callback(null, obj);
    })
}


exports.moneyWhere = moneyWhere;

async function moneyWhere(objectId, name, receiver, orderCode, shopName, buyerName, buyerOId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_order');

    if (name != "" && name != undefined && name != null) {
        query.equalTo("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (receiver != "" && receiver != undefined && receiver != null) {
        query.equalTo("receiver", receiver);
    }
    if (orderCode != "" && orderCode != undefined && orderCode != null) {
        query.equalTo("orderCode", Number(orderCode));
    }

    if (shopName != "" && shopName != undefined && shopName != null) {
        function find(shopUser) {
            var User = new AV.Query('Shop_shop');
            User.contains('name', shopUser);
            var seller = User.find().then(function (resullt) {
                var sellerArr = [];
                for (var i = 0; i < resullt.length; i++) {
                    var sellerQuery = resullt[i].get("objectId");
                    sellerArr.push(sellerQuery);
                }
                return query.containedIn("shopOId", sellerArr);
            }, function (reject) {
                return reject
            }).catch(function (error) {
                callback(error, null);
            });
            return seller;
        }

        await find(shopName);
    }
    if (buyerName != "" && buyerName != undefined && buyerName != null) {
        let buyArr = await findBuyer(buyerName);
        query.containedIn("buyerOId", buyerArr);
    }
    if (buyerOId != "" && buyerOId != undefined && buyerOId != null) {
        query.equalTo("buyerOId", buyerOId);
    }

    let status = [0, 1, null]
    query.skip((page - 1) * num);
    query.limit(num);
    query.notContainedIn("status", status);
    query.include('payInfo');
    query.include('shopObj');
    query.include('buyerObj');
    query.include('sellerObj');
    query.include('fightGroupObj');
    query.include('orderGoodsArray');
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(async function (count) {
                var obj = {};
                var start = async function () {
                    var data = [];
                    for (var i = 0; i < result.length; i++) {
                        var goodsObj = await sleep(result[i]);
                        data.push(goodsObj)
                    }
                    return data;
                };

                function sleep(order) {
                    var goods = new AV.Query('Shop_order_goods');
                    goods.equalTo("orderOId", order.id);
                    var goodsInfor = goods.first().then(async function (goods) {
                        //物流信息
                        var temObj = {};
                        temObj["objectId"] = order.id;
                        temObj["orderCode"] = order.get("orderCode");
                        temObj["receiver"] = order.get("receiver");
                        temObj["status"] = order.get("status");
                        temObj["createdAt"] = moment(order.createdAt).format('YYYY-MM-DD HH:mm:ss');
                        temObj["payTime"] = order.get("payTime");
                        temObj["totalPrice"] = order.get("totalPrice");
                        temObj["phone"] = order.get("phone");
                        temObj["payType"] = order.get("payType");
                        temObj["address"] = order.get("address");
                        temObj["expressCode"] = order.get("expressCode");
                        temObj["logisticsCom"] = order.get("logisticsCom");
                        temObj["deliverTime"] = order.get("deliverTime");
                        temObj["sellerOId"] = order.get("sellerOId");
                        temObj["shopName"] = order.get("shopObj") ? order.get("shopObj").get("name") : '';
                        temObj["shopUserName"] = order.get("sellerObj") ? order.get("sellerObj").get("nickName") : '';
                        temObj["buyerId"] = order.get("buyerObj") ? order.get("buyerObj").id : '';
                        temObj["buyerAvatar"] = order.get("buyerObj") ? order.get("buyerObj").get("userAvatar") ? order.get("buyerObj").get("userAvatar").url() : '' : '';
                        temObj["buyerName"] = order.get("buyerObj") ? order.get("buyerObj").get("nickName") : '';
                        temObj["fare"] = order.get("fare");
                        temObj["goodsOId"] = {};
                        let incomMoney = await whereMoneyAdd(temObj["orderCode"]) + order.get("fare");
                        let totalPrice = order.get("totalPrice");
                        incomMoney = Math.round(incomMoney * 100);
                        totalPrice = Math.round(totalPrice * 100);
                        let incomTotalMoney = incomMoney / 100
                        temObj["incomTotalMoney"] = incomTotalMoney;
                        if (incomMoney == totalPrice) {
                            temObj["moneyStatus"] = 1;
                        } else {
                            temObj["moneyStatus"] = 0;
                        }
                        if (order.get("fightGroupObj") != undefined) {
                            temObj["goodsOId"]["status"] = "group"
                            temObj["goodsOId"]["objectId"] = order.get("fightGroupObj").get("objectId");
                        }
                        if (goods != '' && goods != undefined && goods != null) {
                            temObj["goodsPicURL"] = goods.get("goodsPicURL") ? goods.get("goodsPicURL") : "";
                            temObj["num"] = goods.get("num");
                            temObj["goodsOriginPrice"] = goods.get("goodsOriginPrice");
                            temObj["goodsModel"] = goods.get("goodsModel");
                            temObj["goodsName"] = goods.get("goodsName");
                            temObj["price"] = goods.get("price");
                            if (order.get("fightGroupObj") == undefined) {
                                temObj["goodsOId"]["status"] = "app"
                                temObj["goodsOId"]["objectId"] = goods.get("goodsOId");
                            }
                            temObj["groupPrice"] = goods.get("groupPrice");
                        }
                        return temObj
                    }).catch(function (err) {
                        console.log(err)
                    });
                    return goodsInfor;
                }

                function whereMoneyAdd(orderNo) {
                    let moneyQuery = new AV.Query("Shop_account_detail");
                    moneyQuery.equalTo("orderNo", Number(orderNo));
                    let MoneyQuery = moneyQuery.find().then((result) => {
                        let money = 0;
                        for (let i = 0; i < result.length; i++) {
                            money = money + Number(result[i].get("changeMoney"));
                        }
                        return money;
                    })
                    return MoneyQuery;
                }

                var resultArr = await start();
                obj.data = resultArr;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
};


exports.userMergedList = userMergedList;

async function userMergedList(saveUserOId, saveUserName, delUserOId, delUserName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('userMerged');

    if (saveUserOId != "" && saveUserOId != undefined && saveUserOId != null) {
        query.equalTo("saveUserOId", saveUserOId);
    }
    if (delUserOId != "" && delUserOId != undefined && delUserOId != null) {
        query.equalTo("delUserOId", delUserOId);
    }
    if (saveUserName != "" && saveUserName != undefined && saveUserName != null) {
        let Users = await new findUser(saveUserName);
        query.containedIn("saveUserOId", Users);
    }
    if (delUserName != "" && delUserName != undefined && delUserName != null) {
        let Users = await findUser(delUserName);
        query.containedIn("delUserOId", Users);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt")
    query.include("saveUserObj");
    query.include("delUserObj");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["hasSync"] = item.get("hasSync");
                temObj["syncType"] = item.get("syncType");
                temObj["saveUserOId"] = item.get("saveUserOId");
                temObj["saveUserName"] = item.get("saveUserObj") ? item.get("saveUserObj").get("nickName") : "";
                temObj["saveUserAvatar"] = item.get("saveUserObj").get("userAvatar") ? item.get("saveUserObj").get("userAvatar").url() : "";
                temObj["delUserOId"] = item.get("delUserOId");
                temObj["delUserName"] = item.get("delUserObj") ? item.get("delUserObj").get("nickName") : "";
                temObj["delUserAvatar"] = item.get("delUserObj").get("userAvatar") ? item.get("delUserObj").get("userAvatar").url() : "";
                temObj["status"] = item.get("status");
                temObj["bingingPhone"] = item.get("bingingPhone");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};


exports.suggestionList = suggestionList;

async function suggestionList(phoneNum, type, status, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('suggestion');
    if (phoneNum != "" && phoneNum != undefined && phoneNum != null) {
        query.equalTo("phoneNum", phoneNum);
    }
    if (type != "" && type != undefined && type != null) {
        query.equalTo("type", type);
    }
    if (status != "" && status != undefined && status != null) {
        query.equalTo("status", Number(status));
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt")
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["content"] = item.get("content");  //建议内容
                temObj["picArr"] = imageArr(item.get("picArr"));//图片
                temObj["phoneNum"] = item.get("phoneNum");//电话
                temObj["type"] = item.get("type")//类型
                temObj["status"] = item.get("status")//0未处理，1解决，2处理中
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.relateGoodsInformation = relateGoodsInformation;

function relateGoodsInformation(objectId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Shop_goods');
    query.containedIn("objectId", objectId);
    query.skip((page - 1) * num);
    query.limit(num);
    query.include('shopObj');
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(function (count) {
                var obj = {};
                var data = [];
                var qn = 'http://tribemedia.aladada.com/';
                // var picOIdArr=[];
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["recommend"] = result[i].get("recommend");//店长推荐
                    temObj["groupBuying"] = result[i].get("groupBuying");//能否团购
                    temObj["promotePrice"] = result[i].get("promotePrice");//推广佣金
                    temObj["shopName"] = result[i].get("shopObj") ? result[i].get("shopObj").get("name") : "";
                    temObj["groupPrice"] = result[i].get("groupPrice");
                    temObj["saleNums"] = result[i].get("saleNums");//销量
                    temObj["title"] = result[i].get("title");//名称
                    temObj["originalPrice"] = result[i].get("originalPrice");//原价
                    temObj["status"] = result[i].get("status");//-1删除 0下架 1上架
                    temObj["freePost"] = result[i].get("freePost");//包邮
                    temObj["shopOId"] = result[i].get("shopOId");//店铺Id
                    temObj["describe"] = result[i].get("describe");//描述
                    temObj["discount"] = result[i].get("discount");//折扣
                    temObj["price"] = result[i].get("price");//价格
                    temObj["customize"] = result[i].get("customize");//订制 1可以 -1不可以
                    temObj["stock"] = result[i].get("stock");//库存
                    temObj["createdAt"] = moment(result[i].createdAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["shopIcon"] = result[i].get("picName") ? qn + result[i].get("picName") : "";
                    data.push(temObj);
                }

                obj.data = data;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
}


exports.updateSuggestion = updateSuggestion;

function updateSuggestion(req, callback) {
    var Sug = AV.Object.createWithoutData('suggestion', req.params.objectId);
    Sug.set('status', Number(req.params.status));
    // 保存到云端
    Sug.save().then(function (success) {
            callback(null, success);
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
}

exports.adminUser = adminUser;

async function adminUser(userOId, nickName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    var query = new AV.Query('Admin_user');
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        let Users = await findUser(nickName);
        console.log(Users, "=====Users");
        query.containedIn("userOId", Users);
    }
    query.skip((page - 1) * num);
    query.limit(num);
    query.include("userObj")
    query.descending('createdAt');
    query.find().then(function (result) {
            query.count().then(function (count) {
                console.log(result, "result=========")
                var obj = {};
                var data = [];
                for (let item of result) {
                    var temObj = {};
                    temObj["objectId"] = item.id;
                    temObj["userOId"] = item.get("userOId");
                    temObj["uid"] = item.get("userObj").get("uid");
                    temObj["username"] = item.get("userObj").get("username");
                    temObj["regisFrom"] = item.get("userObj").get("regisFrom");
                    temObj["gender"] = item.get("userObj").get("userAvatar") ? item.get("userObj").get("userAvatar").url() : "";
                    temObj["mobilePhoneNumber"] = item.get("userObj").get("mobilePhoneNumber");
                    temObj["live_authority"] = item.get("userObj").get("live_authority");
                    temObj["verify_authority"] = item.get("userObj").get("verify_authority");
                    temObj["createAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["nickName"] = item.get("userObj").get("nickName");
                    temObj["phoneRegVerify"] = item.get("userObj").get("phoneRegVerify");
                    temObj["status"] = item.get("status");
                    temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                    temObj["province"] = item.get("userObj").get("province");
                    temObj["city"] = item.get("userObj").get("city");
                    temObj["qrCode"] = item.get("userObj").get("qrCode") ? item.get("userObj").get("qrCode").url() : "";
                    temObj["userType"] = item.get("userObj").get("userType");
                    temObj["signature"] = item.get("userObj").get("signature");
                    data.push(temObj);
                }
                obj.data = data;
                obj.total = count;
                callback(null, obj);
            })
        }, function (error) {
            console.log(error);
            callback(error, null);
        }
    )
}

function formatDateTime(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '年' + m + '月' + d + '日';
};

function findUser(userName) {
    var User = new AV.Query('_User')
    User.limit(1000);
    User.contains("nickName", userName);
    return User.find().then((result) => {
        let userArr = [];
        for (let item of result) {
            userArr.push(item.id);
        }
        return userArr;
    }, (reject) => {
        console.log(reject);
        return reject;
    })
}

function findGoods(title) {
    var Goods = new AV.Query('Shop_goods')
    Goods.limit(1000);
    Goods.contains("title", title);
    return Goods.find().then((result) => {
        let goodsArr = [];
        for (let item of result) {
            goodsArr.push(item.id);
        }
        return goodsArr;
    }, (reject) => {
        console.log(reject);
        return reject;
    })
}

function findUserInfo(userOId) {
    var User = new AV.Query('_User')
    User.containedIn("objectId", userOId);
    return User.find().then((result) => {
        let userArr = [];
        for (let item of result) {
            let temObj = {};
            temObj.userOId = item.id;
            temObj.nickName = item.get("nickName");
            temObj.userAvatar = item.get("userAvatar") ? item.get("userAvatar").url() : "";
            userArr.push(temObj);
        }
        return userArr;
    }, (reject) => {
        console.log(reject);
        return reject;
    })
}

function imageArr(picArr) {
    let picArrList = [];
    for (let item of picArr) {
        picArrList.push(apis['qiniu']['url'] + "/" + item)
    }
    return picArrList;
}

exports.addAdmin = addAdmin;

async function addAdmin(req, callback) {
    let objectId = req.params.objectId;
    if (objectId != "" && objectId != undefined && objectId != null) {
        var User = AV.Object.createWithoutData("Admin_user", objectId);
    } else {
        var repeatRes = await repeat(req.params.userOId);
        if (repeatRes == 1) {
            var Users = AV.Object.extend("Admin_user");
            var User = new Users;
            var userObj = AV.Object.createWithoutData("_User", req.params.userOId);
            User.set("userObj", userObj);
            User.set("userOId", req.params.userOId);
        } else {
            return callback(null, "10003")
        }
    }
    User.set("status", Number(req.params.status));
    User.save().then((result) => {
        callback(null, "10001")
    }, (reject) => {
        callback(reject, "10002")
    });
}

function repeat(objectId) {
    let query = new AV.Query("Admin_user")
    query.equalTo("userOId", objectId)
    return query.first().then((result) => {
        if (result != "" && result != null) {
            return 0  //授权过
        } else {
            return 1  //未授权
        }
    })
}

exports.wxGroupType = wxGroupType;

async function wxGroupType(objectId, name, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('wx_group_type');
    if (name != "" && name != undefined && name != null) {
        query.contains("name", name);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt")
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["name"] = item.get("name");  //分类名称
                temObj["sign"] = item.get("sign");
                temObj["qrCode"] = item.get("qrCode") ? item.get("qrCode").url() : "";//二维码
                temObj["classiftyTitle"] = item.get("classiftyTitle");//群名
                temObj["classiftyDescribe"] = item.get("classiftyDescribe")//描述
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.wxGroupTypeBelong = wxGroupTypeBelong;

async function wxGroupTypeBelong(wxGroupType, name, objectId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('wx_group');
    if (name != "" && name != undefined && name != null) {
        query.contains("name", name);
    }
    if (wxGroupType != "" && wxGroupType != undefined && wxGroupType != null) {
        query.equalTo("wx_group_typeOId", wxGroupType);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt")
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["name"] = item.get("name");  //群名称
                temObj["qrCode"] = item.get("qrcode").url();//二维码
                temObj["wxGroupType"] = item.get("wx_group_typeOId");
                temObj["isFull"] = item.get("isFull")//描述
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

// exports.wxGroupChange=wxGroupChange;
// async function wxGroupChange(req,callback) {
//     var form = new multiparty.Form();
//     form.parse(req,async function (err, fields, files) {
//         var name = fields.name?fields.name[0]:"";
//         var objectId = fields.objectId?fields.objectId[0]:"";
//         var groupType = fields.groupType?fields.groupType[0]:"";
//         var qrcode =   files.Fdata[0].size?files.Fdata[0]:"";
//         if(objectId!=""&&objectId!=null){
//             var wxGroup = AV.Object.createWithoutData("wx_group",objectId)
//         }else{
//             var wxGroups = AV.Object.extend('wx_group');
//             var wxGroup = new wxGroups();
//             var wx_group_typeObj = AV.Object.createWithoutData("wx_group_type",groupType)
//         }
//         if(qrcode!=""&&qrcode!=null){
//             let saveFiles = await saveFile(qrcode.path);
//             wxGroup.save("qrcode",saveFiles)
//         }
//         if(groupType!=""&&groupType!=null){
//             wxGroup.set("wx_group_typeOId", groupType);
//         }
//         wxGroup.set("name", name);
//         wxGroup.set("wx_group_typeObj", wx_group_typeObj);
//         wxGroup.save().then(function (result) {
//             callback(null,"10001");
//         },function (reject) {
//             console.log(reject);
//             callback(reject,"10002")
//         }).catch(function (err) {
//             console.log(err);
//             callback(err,"10002")
//         })
//     })
// }
function saveFile(filePath) {
    return new Promise((resolve, reject) => {
        fs.readFile(filePath, function (err, data) {
            var key = uuid.v1().replace(/-/g, "") + ".jpg";
            var saveFile = new AV.File(key, data);
            resolve(saveFile);
        })
    })
}

exports.wxGroupoTypeChange = wxGroupoTypeChange;

function wxGroupoTypeChange(req, callback) {

    var wx_group = AV.Object.extend("wx_group_type");

    var group = new wx_group();

    group.set("name", req.params.name);
    group.set("classiftyDescribe", req.params.classiftyDescribe);
    group.set("classiftyTitle", req.params.classiftyTitle);


    group.save().then(function (group) {
        // response.redirect("/back/wxGroupClassifty");
        var sign = group.id;
        var url = "http://h5.aladada.com/enterGroup?sign=" + sign;
        var qrAPI = "https://leancloud.cn/1.1/qrcode?url=" + url + "&width=600&height=600";

        var nameImage = "classifty_qrCode_" + new Date().getTime() + ".jpg";
        var nameQrcode = new Date().getTime();

        qiniuServer.getQrcodeUrl(nameImage, qrAPI, function (err, newQrCode) {

            if (!err) {
                var File = AV.Object.extend("_File");
                var file = new File();
                file.set("url", apis['qiniu']['url'] + "/" + newQrCode);
                file.set("name", String(nameQrcode));
                file.save().then(function (file) {

                        var query = new AV.Query("wx_group_type");
                        query.equalTo("objectId", sign);
                        query.first().then(function (wxObj) {
                            if (wxObj) {


                                wxObj.set("sign", wxObj.id);
                                wxObj.set("qrCode", file);
                                wxObj.save().then(function (group) {

                                    callback(null, "10001")
                                }, function (error) {
                                    console.log(error)
                                    // console.log(JSON.stringify(error));
                                })
                            } else {
                                callback(null, "10002")
                            }


                        })

                    }
                )
            } else {
                console.log('failed');
            }
        }, function (error) {

            console.log(JSON.stringify(error));

        });

    }, function (error) {
        // console.log(JSON.stringify(error));
    })
}

exports.wxGroupoTypeUpdate = wxGroupoTypeUpdate;

function wxGroupoTypeUpdate(req, callback) {
    var group = AV.Object.createWithoutData("wx_group_type", req.params.objectId);
    group.set("name", req.params.name);
    group.set("classiftyDescribe", req.params.classiftyDescribe);
    group.set("classiftyTitle", req.params.classiftyTitle);
    group.save().then((resolve) => {
        callback(null, "10001")
    })
}

exports.wxGroupChange = wxGroupChange;

async function wxGroupChange(base64, name, objectId, groupType, callback) {
    //接收前台POST过来的base64
    //过滤data:URL
    if (objectId != "" && objectId != null) {
        var wxGroup = AV.Object.createWithoutData("wx_group", objectId)
    } else {
        var wxGroups = AV.Object.extend('wx_group');
        var wxGroup = new wxGroups();
        var wx_group_typeObj = AV.Object.createWithoutData("wx_group_type", groupType);
        wxGroup.set("wx_group_typeOId", groupType);
        wxGroup.set("wx_group_typeObj", wx_group_typeObj);
    }
    if (base64 != "" && base64 != null) {
        let base64Data = base64.replace(/^data:image\/\w+;base64,/, "");
        let dataBuffer = new Buffer(base64Data, 'base64');
        let saveFiles = await bufferFile(dataBuffer);
        wxGroup.save("qrcode", saveFiles)
    }
    wxGroup.set("name", name);
    wxGroup.save().then(function (result) {
        callback(null, "10001");
    }, function (reject) {
        console.log(reject);
        callback(reject, "10002")
    }).catch(function (err) {
        console.log(err);
        callback(err, "10002")
    })
}

function bufferFile(filePath) {
    return new Promise((resolve, reject) => {
        var key = uuid.v1().replace(/-/g, "") + ".jpg";
        var saveFile = new AV.File(key, filePath);
        resolve(saveFile);
    })
}

exports.findTemplateForThread = findTemplateForThread;

function findTemplateForThread(objectId, page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('template_For_Thread');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("webappOId", objectId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["content"] = item.get("content");
                temObj["name"] = item.get("name");
                temObj["webAppOId"] = item.get("webappOId");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.addTemplateForThread = addTemplateForThread;

function addTemplateForThread(webappOId, content, name) {
    let TemForThread = AV.Object.extend('template_For_Thread');
    let webappObj = AV.Object.createWithoutData('WeApp_version', webappOId);
    let temForThread = new TemForThread();
    temForThread.set('content', content);
    temForThread.set('name', name);
    temForThread.set('webappOId', webappOId);
    temForThread.set('webappObj', webappObj);
    return temForThread.save().then(function (result) {
        return result;
    }, function (error) {
        console.log(error);
    })
}

exports.selTemplateForThread = selTemplateForThread;

function selTemplateForThread(objectId) {
    let query = new AV.Query('template_For_Thread');
    return query.get(objectId).then(function (result) {
        return result;
    }, function (error) {
        console.log(error)
    })
}

exports.editTemplateForThread = editTemplateForThread;

function editTemplateForThread(objectId, content, name) {
    let query = AV.Object.createWithoutData('template_For_Thread', objectId);
    query.set('content', content);
    query.set('name', name);
    return query.save().then(function (result) {
        return result;
    }, function (error) {
        console.log(error);
    })
}

exports.deleteTemplateForThread = deleteTemplateForThread;

function deleteTemplateForThread(objectId, callback) {
    let query = AV.Object.createWithoutData('template_For_Thread', objectId);
    query.destroy().then(resolve => {
        callback(null, "10001")
    }, reject => {
        callback(reject, "10002")
    })

}

exports.getUserIdentifyProp = getUserIdentifyProp;

function getUserIdentifyProp(data) {
    var page = data.page
    var num = data.num
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('IdentifyProp');
    // if(objectId !="" && objectId !=undefined && objectId !=null){
    //   query.equalTo("webappOId",objectId);
    // }
    query.limit(num);
    query.skip((page - 1) * num);
    query.equalTo('status', 0)
    query.descending("createAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            // console.log(result)
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["name"] = item.get("name");
                temObj["category"] = item.get("category");
                temObj["type"] = item.get("type");
                temObj["tableField"] = item.get("tableField");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(err => {
            console.log(err)
        })
    }).catch(error => {
        console.log(error)
    })
}

exports.getUserIdentifyPropForId = getUserIdentifyPropForId;

function getUserIdentifyPropForId(objectId) {
    let query = new AV.Query('IdentifyProp');
    query.equalTo('objectId', objectId)
    query.descending("createAt");
    return query.first().then(function (item) {
        if (item) {
            let obj = {};
            obj["objectId"] = item.get("objectId");
            obj["name"] = item.get("name");
            obj["category"] = item.get("category");
            obj["type"] = item.get("type");
            obj["tableField"] = item.get("tableField");
            return obj;
        } else {
            console.log('没有找到ID对应对象！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.userIdentifyPropAdd = userIdentifyPropAdd;

async function userIdentifyPropAdd(data) {
    let IdentifyProp = AV.Object.extend("IdentifyProp");
    let identifyProp = new IdentifyProp;
    identifyProp.set("name", data.name);
    identifyProp.set("category", data.category);
    identifyProp.set("type", Number(data.type));
    identifyProp.set("tableField", data.tableField);
    identifyProp.set("status", 0);
    return identifyProp.save().then(result => {
        // console.log(result)
        if (result) {
            return result
        } else {
            console.log('保存失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.userIdentifyPropUpdate = userIdentifyPropUpdate;

async function userIdentifyPropUpdate(data) {
    let objectId = data.objectId
    let name = data.name
    let category = data.category
    let type = data.type
    let status = data.status
    let tableField = data.tableField
    var identifyProp = AV.Object.createWithoutData("IdentifyProp", objectId);
    if (name != "" && name != undefined && name != null) {
        identifyProp.set("name", name);
    }
    if (category != "" && category != undefined && category != null) {
        identifyProp.set("category", category);
    }
    if (tableField != "" && tableField != undefined && tableField != null) {
        identifyProp.set("tableField", tableField);
    }
    if (type != "" && type != undefined && type != null) {
        identifyProp.set("type", Number(type));
    }
    if (status != "" && status != undefined && status != null) {
        identifyProp.set("status", Number(status));
    }
    return identifyProp.save().then(result => {
        if (result) {
            return result
        } else {
            console.log('保存失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.getUserIdentifyPropRelation = getUserIdentifyPropRelation;

function getUserIdentifyPropRelation(data) {
    var page = data.page
    var num = data.num
    var identifyPropOId = data.objectId
    if (identifyPropOId == '' || identifyPropOId == undefined || identifyPropOId == null) {
        console.log('未获取到用户属性ID!')
        return null
    }
    if (page == '' || page == undefined || page == null) {
        page = 1;
    }
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('IdentifyPropRelation');
    query.limit(num);
    query.skip((page - 1) * num);
    query.equalTo('identifyPropOId', identifyPropOId)
    query.equalTo('status', 0)
    query.include('tribeObj')
    query.include('identifyPropObj')
    query.descending("createAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            // console.log(result)
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["tribeOId"] = item.get("tribeOId");
                temObj["tribeName"] = item.get("tribeObj").get('name');
                temObj["tribeStatus"] = item.get("tribeObj").get('status');        //-1删除0锁定1正常
                temObj["tribeAvator"] = item.get("tribeObj").get("tribeAvator") ? item.get("tribeObj").get("tribeAvator").url() : "";
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(err => {
            console.log(err)
        })
    }).catch(error => {
        console.log(error)
    })
}

exports.userIdentifyPropRelationAdd = userIdentifyPropRelationAdd;

async function userIdentifyPropRelationAdd(data) {
    let identifyPropOId = data.objectId
    let tribeOId = data.tribeOId
    if (identifyPropOId == '' || identifyPropOId == undefined || identifyPropOId == null) {
        console.log('未获得用户属性ID！')
        return null
    } else {
        var identifyPropObj = AV.Object.createWithoutData('IdentifyProp', identifyPropOId);
    }
    if (tribeOId == '' || tribeOId == undefined || tribeOId == null) {
        console.log('未获得部落ID！')
        return null
    } else {
        var tribeObj = AV.Object.createWithoutData('Tribe', tribeOId);
    }
    let IdentifyPropRelation = AV.Object.extend("IdentifyPropRelation");
    let identifyPropRelation = new IdentifyPropRelation;
    identifyPropRelation.set("identifyPropOId", identifyPropOId);
    identifyPropRelation.set("identifyPropObj", identifyPropObj);
    identifyPropRelation.set("tribeOId", tribeOId);
    identifyPropRelation.set("tribeObj", tribeObj);
    identifyPropRelation.set("status", 0);
    return identifyPropRelation.save().then(result => {
        if (result) {
            return result
        } else {
            console.log('保存失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.userIdentifyPropRelationRemove = userIdentifyPropRelationRemove;

function userIdentifyPropRelationRemove(objectId, callback) {
    let query = AV.Object.createWithoutData('IdentifyPropRelation', objectId);
    query.destroy().then(resolve => {
        callback(null, "10001")
    }, reject => {
        callback(reject, "10002")
    })
}

exports.getIntegralRatio = getIntegralRatio;

function getIntegralRatio(data) {
    var page = data.page
    var num = data.num
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('subscription_ratio');
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createAt");
    return query.find().then(function (result) {
        // console.log(result)
        return query.count().then(function (count) {
            // console.log(result)
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["coin"] = item.get("coin");
                temObj["rmb"] = item.get("rmb");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(err => {
            console.log(err)
        })
    }).catch(error => {
        console.log(error)
    })
}

exports.getIntegralRatioForId = getIntegralRatioForId;

function getIntegralRatioForId(objectId) {
    let query = new AV.Query('subscription_ratio');
    query.equalTo('objectId', objectId)
    query.descending("createAt");
    return query.first().then(function (item) {
        if (item) {
            let obj = {};
            obj["objectId"] = item.get("objectId");
            obj["coin"] = item.get("coin");
            obj["rmb"] = item.get("rmb");
            return obj;
        } else {
            console.log('没有找到ID对应对象！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.integralRatioUpdate = integralRatioUpdate;

async function integralRatioUpdate(data) {
    let objectId = data.objectId
    let coin = data.coin
    let rmb = data.rmb
    var integralRatio = AV.Object.createWithoutData("subscription_ratio", objectId);
    if (coin != "" && coin != undefined && coin != null) {
        integralRatio.set("coin", Number(coin));
    }
    if (rmb != "" && rmb != undefined && rmb != null) {
        integralRatio.set("rmb", Number(rmb));
    }
    return integralRatio.save().then(result => {
        if (result) {
            return result
        } else {
            console.log('保存失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.shopTypeList = shopTypeList;

async function shopTypeList(objectId, type, typeName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_type');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (type != "" && type != undefined && type != null) {
        query.equalTo("type", type);
    }
    if (typeName != "" && typeName != undefined && typeName != null) {
        query.contains("typeName", typeName);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt");
    query.notEqualTo("status", "-1")
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["typeName"] = item.get("typeName");
                temObj["status"] = item.get("status");
                temObj["type"] = item.get("type");
                temObj["picURL"] = apis['qiniu']['url'] + "/" + item.get("picURL");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.shopTypeGoodsList = shopTypeGoodsList;

async function shopTypeGoodsList(objectId, shopTypeOId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_type_good_relation');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (shopTypeOId != "" && shopTypeOId != undefined && shopTypeOId != null) {
        query.equalTo("shopTypeOId", shopTypeOId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt");
    query.notEqualTo("status", "-1");
    query.include('shopGoodsObj');
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["shopGoodsOId"] = item.get("shopGoodsOId");
                temObj["promotePrice"] = item.get("shopGoodsObj").get("promotePrice");//推广佣金
                temObj["groupPrice"] = item.get("shopGoodsObj").get("groupPrice");
                temObj["saleNums"] = item.get("shopGoodsObj").get("saleNums");//销量
                temObj["title"] = item.get("shopGoodsObj").get("title");//名称
                temObj["originalPrice"] = item.get("shopGoodsObj").get("originalPrice");//原价
                temObj["status"] = item.get("shopGoodsObj").get("status");//-1删除 0下架 1上架
                temObj["describe"] = item.get("shopGoodsObj").get("describe");//描述
                temObj["discount"] = item.get("shopGoodsObj").get("discount");//折扣
                temObj["price"] = item.get("shopGoodsObj").get("price");//价格
                temObj["stock"] = item.get("shopGoodsObj").get("stock");//库存
                temObj["picName"] = apis['qiniu']['url'] + "/" + item.get("shopGoodsObj").get("picName");//库存
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.classificationGoodsAdd = classificationGoodsAdd;

function classificationGoodsAdd(shopTypeOId, shopGoodsOId, callback) {
    var query = new AV.Query('Shop_type_good_relation');
    query.equalTo('shopGoodsOId', shopGoodsOId);
    query.first().then(function (objects) {
        if (objects != "" && objects != undefined) {
            if (objects.get("status") == -1) {
                objects.set("status", "0").save().then((result) => {
                        return callback(null, "10001")
                    }, (error) => {
                        return callback(error, "10003")
                    }
                )
            } else {
                return callback(null, "10002");
            }
        } else {
            var RelationGoods = AV.Object.extend("Shop_type_good_relation");
            var relationGoods = new RelationGoods;
            var shopGoodsObj = AV.Object.createWithoutData("Shop_goods", shopGoodsOId);
            var shopTypeObj = AV.Object.createWithoutData("Shop_type", shopTypeOId);
            relationGoods.set("shopGoodsObj", shopGoodsObj);
            relationGoods.set("shopGoodsOId", shopGoodsOId);
            relationGoods.set("shopTypeOId", shopTypeOId);
            relationGoods.set("shopTypeObj", shopTypeObj);
            relationGoods.set("status", "0");
            relationGoods.save().then(function (result) {
                callback(null, "10001")
            })
        }
    }, function (error) {
        console.log(error);
        callback(error, "10003")
    })

}

exports.updateShopType = updateShopType;
async function updateShopType(req, callback) {
    var form = new multiparty.Form();

    form.parse(req, async function (err, fields, files) {
        var typeName = fields.typeName ? fields.typeName[0] : null;
        var type = fields.type ? fields.type[0] : null;
        var objectId = fields.objectId ? fields.objectId[0] : null;
        var pic = files.Fdata[0].size ? files.Fdata[0] : null;
        var key = uuid.v1().replace(/-/g, "") + ".png";
        if (objectId != "" && objectId != null) {
            var ShopType = AV.Object.createWithoutData("Shop_type", objectId)
        } else {
            var ShopTypes = AV.Object.extend("Shop_type");
            var ShopType = new ShopTypes();
        }
        if (pic != "" && pic != null) {
            var status = await uploadImg(pic.path, key);
            if (status == 200) {
                ShopType.set("picURL", key);
            }
        }
        ShopType.set("typeName", typeName);
        ShopType.set("type", type);
        ShopType.save().then(function (shop) {
            callback(null, "10001");
        })
    })

}


exports.addBanner = addBanner;
async function addBanner(req, callback) {
    var form = new multiparty.Form();
    form.parse(req, async function (err, fields, files) {
        var typeName = fields.typeName ? fields.typeName[0] : null;
        var type = fields.type ? fields.type[0] : null;
        var objectId = fields.objectId ? fields.objectId[0] : null;
        var shopGoodTypeId = fields.shopGoodTypeId ? fields.shopGoodTypeId[0] : null;


        var pic = files.Fdata[0].size ? files.Fdata[0] : null;
        var key = uuid.v1().replace(/-/g, "") + ".png";


        if (objectId != "" && objectId != null) {
            var goodsBanner = AV.Object.createWithoutData("goods_banner", objectId)
        } else {
            var GoodsBanner = AV.Object.extend("goods_banner");
            var goodsBanner = new GoodsBanner();
        }
        if (pic != "" && pic != null) {
            console.log(key)
            return qn.uploadImg(pic.path, key, function (err, result) {
                if (result == 200) {
                    goodsBanner.set("name", typeName);

                    goodsBanner.set("picUrl", key);
                    goodsBanner.set("shopGoodsTypeOId", shopGoodTypeId);
                    var shopGoodTypeObj = AV.Object.createWithoutData('Shop_good_type',shopGoodTypeId);
                    goodsBanner.set("shopGoodsTypeObj", shopGoodTypeObj);
                    goodsBanner.save().then(function (shop) {
                        return callback(null, "10000");
                    }).catch(error=>{
                        console.log(error)
                        return callback(null, "10001");

                    })

                }
                return callback(null, "10001");
            })

        }else{
            return callback(null, "10001");
        }

    })
}



exports.editBanner = editBanner;
async function editBanner(req, callback) {
    var form = new multiparty.Form();
    form.parse(req, async function (err, fields, files) {
        var typeName = fields.typeName ? fields.typeName[0] : null;
        var type = fields.type ? fields.type[0] : null;
        var objectId = fields.objectId ? fields.objectId[0] : null;
        var sort = fields.sort ? fields.sort[0] : null;

        var shopGoodTypeId = fields.shopGoodTypeId ? fields.shopGoodTypeId[0] : null;


        var pic = files.Fdata[0].size ? files.Fdata[0] : null;
        var key = uuid.v1().replace(/-/g, "") + ".png";



        console.log(sort)
        var goodsBanner;
        if (objectId != "" && objectId != null) {
            goodsBanner = AV.Object.createWithoutData("goods_banner", objectId)
        } else {
            var GoodsBanner = AV.Object.extend("goods_banner");
            goodsBanner = new GoodsBanner();
        }
        if (pic != "" && pic != null) {
            console.log(key)
            return qn.uploadImg(pic.path, key, function (err, result) {
                if (result == 200) {
                    goodsBanner.set("name", typeName);
                    goodsBanner.set('sort',Number(sort))
                    goodsBanner.set("picUrl", key);
                    goodsBanner.set("shopGoodsTypeOId", shopGoodTypeId);
                    var shopGoodTypeObj = AV.Object.createWithoutData('Shop_good_type',shopGoodTypeId);
                    goodsBanner.set("shopGoodsTypeObj", shopGoodTypeObj);
                    goodsBanner.save().then(function (shop) {
                        return callback(null, "10000");
                    }).catch(error=>{
                        console.log(error)
                        return callback(null, "10001");

                    })

                }
                return callback(null, "10001");
            })

        }else{
            goodsBanner.set("name",typeName)
            goodsBanner.set('sort',Number(sort))

            goodsBanner.save().then(res=>{
                return callback(null, "10000");

            }).catch(error=>{
                return callback(null, "10001");

            })

            return callback(null, "10001");
        }

    })
}

function uploadImg(path, key) {
    return new Promise((resolve, reject) => {
        qn.uploadImg(path, key, function (err, result) {
            if (result == 200) {
                resolve(result)
            }
        })
    })
}

function uploadApk(path, key) {
    return new Promise((resolve, reject) => {
        qnAndroid.uploadApk(path, key, function (err, result) {
            if (result == 200) {
                resolve(result)
            }
        })
    })
}

exports.iosVersion = iosVersion;

async function iosVersion(objectId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Ios_version');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["version"] = item.get("version");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.weAppVersion = weAppVersion;

function weAppVersion(objectId, page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }

    let query = new AV.Query('WeApp_version');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["version"] = item.get("version");
                temObj["name"] = item.get("name");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj
        })
    }).catch(error => {
        console.log(error)
        return null
    })

}

exports.updateWeApp = updateWeApp;

function updateWeApp(req) {
    let {objectId, version} = req.params;
    let Ver = AV.Object.createWithoutData('WeApp_version', objectId);
    Ver.set('version', version);
    return Ver.save().then(function (data) {
        return data
    })
}

//tecShop
exports.getTECShopClassify = getTECShopClassify;

function getTECShopClassify(callback) {
    let query = new AV.Query('Dictionary');
    query.equalTo('type', '14')
    return query.find().then(result => {
        var resultArr = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["text"] = result[i].get("name");
            resultArr.push(temObj);
        }
        callback(resultArr)
    }).catch(error => {
        console.log(error)
    })
}


// function tribeCategory(callback) {
//   var query = new AV.Query('Dictionary');
//   query.equalTo("type", '11');
//   query.find().then(function (result) {
//     var resultArr = [];
//     for (var i = 0; i < result.length; i++) {
//       var temObj = {};
//       temObj["id"] = result[i].get("code");
//       temObj["text"] = result[i].get("name");
//       resultArr.push(temObj);
//     }
//     callback(resultArr)
//   }, function (error) {
//     console.log(error)
//   })
// }
exports.getTECShopGoodsList = getTECShopGoodsList;

function getTECShopGoodsList(page, num, classify) {
    // console.log(classify)
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    let query = new AV.Query('TEC_shop_goods');
    if (classify == '' || classify == undefined || classify == null) {
    } else {
        query.equalTo('classify', classify)
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shopGoodsObj');
    query.include('shopGoodsObj.shopObj');
    query.ascending('sort');
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let shopGoodsVal = item.get("shopGoodsObj");
                let temObj = {};
                temObj["id"] = item.get("objectId");
                temObj["objectId"] = shopGoodsVal ? shopGoodsVal.get('objectId') : '';
                temObj["title"] = shopGoodsVal ? shopGoodsVal.get('title') : '';
                temObj["shopIcon"] = shopGoodsVal ? qn + shopGoodsVal.get('picName') : '';
                temObj["name"] = shopGoodsVal ? shopGoodsVal.get("shopObj").get("name") : '';
                temObj["price"] = item.get('price');
                temObj["freight"] = item.get('freight');
                temObj["score"] = item.get('score');
                temObj["count"] = item.get('count');
                temObj["classify"] = item.get('classify');
                temObj["sort"] = item.get('sort');
                temObj["presentScore"] = item.get('presentScore');
                temObj["superiorMoney"] = item.get('superiorMoney');
                temObj["superiorSuperiorMoney"] = item.get('superiorSuperiorMoney');
                temObj["ancestorsMoney"] = item.get('ancestorsMoney');
                temObj["superiorScore"] = item.get('superiorScore');
                temObj["superiorSuperiorScore"] = item.get('superiorSuperiorScore');
                temObj["ancestorsScore"] = item.get('ancestorsScore');
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.addTECShopGoods = addTECShopGoods;

async function addTECShopGoods(shopGoodsOId, price, score, freight, count, classify, presentScore, superiorMoney, superiorSuperiorMoney, ancestorsMoney, superiorScore, superiorSuperiorScore, ancestorsScore) {
    if (shopGoodsOId != null && shopGoodsOId != '') {
        let shopGoodsObj = AV.Object.createWithoutData('Shop_goods', shopGoodsOId);
        let TECShop = AV.Object.extend('TEC_shop_goods');
        let query = new TECShop();
        // let tecShopGoodsCount = await getTECShopGoodsCount()
        // let sort = Number(tecShopGoodsCount)+1
        query.set('score', score);
        query.set('price', price);
        query.set('freight', freight);
        query.set('shopGoodsOId', shopGoodsOId);
        query.set('shopGoodsObj', shopGoodsObj);
        query.set('count', count);
        query.set('classify', classify);
        // query.set('sort',sort);
        query.set('presentScore', presentScore);
        query.set('superiorMoney', superiorMoney);
        query.set('superiorSuperiorMoney', superiorSuperiorMoney);
        query.set('ancestorsMoney', ancestorsMoney);
        query.set('superiorScore', superiorScore);
        query.set('superiorSuperiorScore', superiorSuperiorScore);
        query.set('ancestorsScore', ancestorsScore);
        return query.save().then(function (result) {
            return result;
        })
    }
}

function getTECShopGoodsCount() {
    let query = new AV.Query('TEC_shop_goods');
    return query.count().then(result => {
        return result
    }).catch(error => {
        console.log(error)
    })
}

exports.selectTECShopGoods = selectTECShopGoods;

function selectTECShopGoods(objectId) {
    if (objectId != null && objectId != '') {
        let query = new AV.Query('TEC_shop_goods');
        return query.get(objectId).then(function (result) {
            return result
        })
    }
}

exports.editTECGoodsShop = editTECGoodsShop;

function editTECGoodsShop(objectId, price, score, freight, count, presentScore, superiorMoney, superiorSuperiorMoney, ancestorsMoney, superiorScore, superiorSuperiorScore, ancestorsScore) {
    let tec_shop_goods = AV.Object.createWithoutData("TEC_shop_goods", objectId);
    tec_shop_goods.set('price', price);
    tec_shop_goods.set('score', score);
    tec_shop_goods.set('freight', freight);
    tec_shop_goods.set('count', count);
    tec_shop_goods.set('presentScore', presentScore);
    tec_shop_goods.set('superiorMoney', superiorMoney);
    tec_shop_goods.set('superiorSuperiorMoney', superiorSuperiorMoney);
    tec_shop_goods.set('ancestorsMoney', ancestorsMoney);
    tec_shop_goods.set('superiorScore', superiorScore);
    tec_shop_goods.set('superiorSuperiorScore', superiorSuperiorScore);
    tec_shop_goods.set('ancestorsScore', ancestorsScore);
    return tec_shop_goods.save().then(function (result) {
        return result;
    })
}

exports.deleteTECShopGoods = deleteTECShopGoods;

async function deleteTECShopGoods(req, callback) {
    let ids = req.body.ids;
    let objects = [];
    for (let objectId of ids) {
        let tecShop = AV.Object.createWithoutData('TEC_shop_goods', objectId);
        objects.push(tecShop);
    }
    AV.Object.destroyAll(objects).then(resolve => {
        callback(null, "10001")
    }, reject => {
        callback(reject, "10002")
    })
}

exports.moveTECShopGoods = moveTECShopGoods;

async function moveTECShopGoods(data, callback) {
    let fromId = data.fromId
    let fromSort = Number(data.fromSort)
    let toId = data.toId
    let toSort = Number(data.toSort)
    let fromObj = AV.Object.createWithoutData('TEC_shop_goods', fromId);
    fromObj.set('sort', toSort)
    let toObj = AV.Object.createWithoutData('TEC_shop_goods', toId);
    toObj.set('sort', fromSort)
    AV.Object.saveAll([fromObj, toObj]).then(result => {
        if (result) {
            callback('10000')
        }
    }).catch(error => {
        console.log(error)
    });
}

//shopIntergation
exports.moveScoreShopGoods = moveScoreShopGoods;
async function moveScoreShopGoods(data, callback) {
    // console.log(data)
    let fromId = data.fromId
    let fromSort = Number(data.fromSort)
    let toId = data.toId
    let toSort = Number(data.toSort)
    if (fromId && fromSort){
        var fromObj = AV.Object.createWithoutData('Score_shop_goods', fromId);
        fromObj.set('sortNum', toSort)
    } else {
        console.log('排序原位置参数错误！')
        callback(false)
    }
    if (toId && toSort) {
        var toObj = AV.Object.createWithoutData('Score_shop_goods', toId);
        toObj.set('sortNum', fromSort)
    } else {
        console.log('排序目标位置参数错误！')
        callback(false)
    }
    if (fromObj && toObj){
        AV.Object.saveAll([fromObj, toObj]).then(result => {
            if (result) {
                callback('10000')
            }
        }).catch(error => {
            console.log(error)
            callback(false)
        });
    } else {
        console.log('排序原位置或目标位置对象错误！')
        callback(false)
    }

}

exports.moveTopScoreShopGoods = moveTopScoreShopGoods;
async function moveTopScoreShopGoods(data, callback) {
    // console.log(data)
    let targetIdArr = data.targetIdArr
    let targetSortNumArr = data.targetSortNumArr
    var changeScoreShopGoodsObjArr = []
    for (let i = 0; i<targetIdArr.length; i++){
        let toChangeObj = AV.Object.createWithoutData('Score_shop_goods', targetIdArr[i]);
        toChangeObj.set('sortNum', Number(targetSortNumArr[i]))
        changeScoreShopGoodsObjArr.push(toChangeObj)
    }
    AV.Object.saveAll(changeScoreShopGoodsObjArr).then(result => {
        if (result) {
            // console.log(result)
            callback('10000')
        }
    }).catch(error => {
        console.log(error)
    });
}

exports.shopSearch = shopSearch;

function shopSearch(page, num, goodsName,goodsParentTypeID) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    let query = new AV.Query('Score_shop_goods');
    if (goodsName == '' || goodsName == undefined || goodsName == null) {
    } else {
      let shopGoodsQuery = new AV.Query('Score_shop_goods');
      let shopGoods = new AV.Query('Shop_goods');
      shopGoods.contains('title', goodsName);
      shopGoodsQuery.matchesQuery('shopGoodsObj', shopGoods);

      let externalGoodsQuery = new AV.Query('Score_shop_goods');
      let externalGoods = new AV.Query('External_goods');
      externalGoods.contains('sourceGoodsName', goodsName);
      externalGoodsQuery.matchesQuery('externalGoodsObj', externalGoods);
      query = AV.Query.or(shopGoodsQuery, externalGoodsQuery);
    }
    if (goodsParentTypeID == '' || goodsParentTypeID == undefined || goodsParentTypeID == null) {
    } else {
        query.equalTo('shopGoodsTypeParentOId',goodsParentTypeID)
    }
    // let statusZeroQuery = new AV.Query('Score_shop_goods');
    // statusZeroQuery.equalTo("status", 0);
    // let statusNullQuery = new AV.Query('Score_shop_goods');
    // statusNullQuery.equalTo("status", null);
    // query = AV.Query.or(statusZeroQuery, statusNullQuery);
    query.notEqualTo("status", -1);
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shopGoodsObj');
    query.include('shopGoodsObj.shopObj');
    query.include('shopGoodsTypeParentObj');
    query.include('shopGoodsTypeObj');
    query.include('externalGoodsObj');
    query.ascending('sortNum');
    return query.find().then(function (result) {
        return query.count().then(async function (count) {
            let obj = {};
            let data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let shopGoodsVal = item.get("shopGoodsObj");
                let temObj = {};
                temObj["id"] = item.get("objectId");
                temObj["name"] = shopGoodsVal ? shopGoodsVal.get("shopObj").get("name") : '';
                temObj["isVip"] = item.get('isVip')?item.get('isVip'):0;
                temObj["price"] = item.get('price');
                temObj["freight"] = item.get('freight');
                temObj["score"] = item.get('score');
                if (item.get('classify') == 2){
                  temObj["classify"] = '站外商品'
                  temObj["objectId"] = item.get('externalGoodsOId')
                  temObj["title"] = item.get('externalGoodsObj') ? item.get('externalGoodsObj').get('sourceGoodsName'):''
                  temObj["shopIcon"] = item.get('externalGoodsObj') ? item.get('externalGoodsObj').get('sourceGoodsIcon'):'';
                } else {
                  temObj["classify"] = '普通商品'
                  temObj["objectId"] = shopGoodsVal ? shopGoodsVal.get('objectId') : '';
                  temObj["title"] = shopGoodsVal ? shopGoodsVal.get('title') : '';
                  temObj["shopIcon"] = shopGoodsVal ? qn + shopGoodsVal.get('picName')+'?imageMogr2/thumbnail/640x/format/jpg/interlace/1/auto-orient' : '';
                }
                temObj["count"] = item.get('count');
                temObj["brokerage"] = item.get('brokerage')?item.get('brokerage'):0;
                temObj["presentScore"] = item.get('presentScore');
                temObj["superiorMoney"] = item.get('superiorMoney');
                temObj["superiorSuperiorMoney"] = item.get('superiorSuperiorMoney');
                temObj["superiorSuperiorSuperiorMoney"] = item.get('superiorSuperiorSuperiorMoney');
                temObj["ancestorsMoney"] = item.get('ancestorsMoney');
                temObj["superiorScore"] = item.get('superiorScore');
                temObj["superiorSuperiorScore"] = item.get('superiorSuperiorScore');
                // temObj["superiorSuperiorSuperiorScore"] = item.get('superiorSuperiorSuperiorScore');
                temObj["ancestorsScore"] = item.get('ancestorsScore');
                let parentGoodsTypeName = item.get('shopGoodsTypeParentObj') ? item.get('shopGoodsTypeParentObj').get('name') : '';
                let goodsTypeName = item.get('shopGoodsTypeObj') ? item.get('shopGoodsTypeObj').get('name') : '';
                if (parentGoodsTypeName != '' && goodsTypeName != ''){
                    temObj['goodsType'] = parentGoodsTypeName + '-' + goodsTypeName;
                } else {
                    temObj['goodsType'] = parentGoodsTypeName;
                }

                temObj["shopGoodsTypeParentOId"] = item.get('shopGoodsTypeParentOId');
                temObj["sortNum"] = item.get('sortNum');
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.getGoodsParentType = getGoodsParentType;
function getGoodsParentType (callback){
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode",'1');
    query.doesNotExist('parentId')
    query.ascending("sortNum");
    query.find().then(function (goodsType) {
        var data = []
        data.push({id:'',text:''})
        goodsType.map(item=>{
            let tempDic = {}
            tempDic.id = item.id
            tempDic.text = item.get('name')
            data.push(tempDic)
        })
        callback(data)
    }, function (error) {
        console.log(error)
    })
}
exports.shopGoodSelect = shopGoodSelect;

function shopGoodSelect(objectId, name, shopName, shopId, page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_goods');
    if (objectId != '' && objectId != undefined && objectId != null) {
        query.equalTo('objectId', objectId);
    }
    if (name != '' && name != undefined && name != null) {
        query.contains('title', name);
    }
    if (shopId != '' && shopId != undefined && shopId != null) {
        query.equalTo('shopOId', shopId);
    }
    if (shopName != '' && shopName != undefined && shopName != null) {
        let shopShop = new AV.Query('Shop_shop');
        shopShop.contains('name', shopName);
        query.matchesQuery('shopObj', shopShop);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            var obj = {};
            var data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get('objectId');
                temObj["title"] = item.get("title");
                temObj["shopIcon"] = item.get("picName") ? qn + item.get("picName") : '';
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}
exports.getScoreShopClassify = getScoreShopClassify;
function getScoreShopClassify(callback) {
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode", '0');
    query.find().then(function (result) {
        var resultArr = [];
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["text"] = result[i].get("name");
            temObj["objectId"] = result[i].get("objectId");
            resultArr.push(temObj);
        }
        callback(resultArr);
    }, function (error) {
        console.log(error);
        callback(error, null);
    })
}
exports.updateScoreGoods = updateScoreGoods;

function updateScoreGoods(data) {
    let shopGoodsOId = data.shopGoodsOId;
    let typeName = data.typeName
    let price = Number(data.price);
    let isVip = Number(data.isVip);
    let score = Number(data.score);
    let freight = Number(data.freight);
    let count = Number(data.count);
    let presentScore = Number(data.presentScore);
    let superiorMoney = Number(data.superiorMoney);
    let superiorSuperiorMoney = Number(data.superiorSuperiorMoney);
    let superiorSuperiorSuperiorMoney = Number(data.superiorSuperiorSuperiorMoney);
    let ancestorsMoney = Number(data.ancestorsMoney);
    let superiorScore = Number(data.superiorScore);
    let superiorSuperiorScore = Number(data.superiorSuperiorScore);
    // let superiorSuperiorSuperiorScore = Number(data.superiorSuperiorSuperiorScore);
    let ancestorsScore = Number(data.ancestorsScore);
    let brokerage = Number(data.brokerage);
    let goodsTypeOId = data.goodsTypeOId;
    var goodsTypeObj = AV.Object.createWithoutData('Shop_good_type', goodsTypeOId);
    let goodsTypePId = data.goodsTypePId;
    if (shopGoodsOId != null && shopGoodsOId != '') {
        let ScoreShop = AV.Object.extend('Score_shop_goods');
        let query = new ScoreShop();
        query.set('score', score);
        query.set('price', price);
        query.set('isVip', isVip);
        query.set('freight', freight);
        if (typeName == '2'){ //站外商品
          let externalGoodsObj = AV.Object.createWithoutData('External_goods', shopGoodsOId);
          query.set('externalGoodsOId', shopGoodsOId);
          query.set('externalGoodsObj', externalGoodsObj);
        } else {
          let shopGoodsObj = AV.Object.createWithoutData('Shop_goods', shopGoodsOId);
          query.set('shopGoodsOId', shopGoodsOId);
          query.set('shopGoodsObj', shopGoodsObj);
        }
        query.set('classify', Number(typeName));
        query.set('count', count);
        query.set('brokerage',brokerage); //佣金总额
        query.set('presentScore', presentScore);
        query.set('superiorMoney', superiorMoney);
        query.set('superiorSuperiorMoney', superiorSuperiorMoney);
        query.set('superiorSuperiorSuperiorMoney', superiorSuperiorSuperiorMoney);
        query.set('ancestorsMoney', ancestorsMoney);
        query.set('superiorScore', superiorScore);
        query.set('superiorSuperiorScore', superiorSuperiorScore);
        // query.set('superiorSuperiorSuperiorScore', superiorSuperiorSuperiorScore);
        query.set('ancestorsScore', ancestorsScore);
        if (goodsTypePId != null && goodsTypePId != '') {
            let goodsTypePObj = AV.Object.createWithoutData('Shop_good_type', goodsTypePId);
            query.set('shopGoodsTypeParentOId', goodsTypePId);
            query.set('shopGoodsTypeParentObj', goodsTypePObj);
            query.set('shopGoodsTypeOId', goodsTypeOId);
            query.set('shopGoodsTypeObj', goodsTypeObj);
        } else {
            query.set('shopGoodsTypeParentOId', goodsTypeOId);
            query.set('shopGoodsTypeParentObj', goodsTypeObj);
        }
        return query.save().then(function (result) {
            return result;
        })
    }
}
exports.addScoreGoodsShopForBatch = addScoreGoodsShopForBatch;
async function addScoreGoodsShopForBatch(data) {
  let goodsObjs = await getExternalGoodsInfoForBatch(data.goodsOIds)
  let goodsTypeOId = data.goodsTypeOId;
  var goodsTypeObj = AV.Object.createWithoutData('Shop_good_type', goodsTypeOId);
  let goodsTypePId = data.goodsTypePId;
  let freight = 0;
  let isVip = 0;
  let score = 0;
  let presentScore = 0;
  let superiorMoney = 0;
  let superiorSuperiorMoney = 0;
  let superiorSuperiorSuperiorMoney = 0;
  let ancestorsMoney = 0;
  let superiorScore = 0;
  let superiorSuperiorScore = 0;
  let ancestorsScore = 0;
  let classify = 2
  if (data.goodsOIds.length > 0) {
    let ScoreShop = AV.Object.extend('Score_shop_goods');
    var objs = []
    for (let item of goodsObjs) {
      let query = new ScoreShop();
      let brokerage = Number(item.get('commission'))
      let count = Number(item.get('SalesVolumeMonth'))
      let price = Number(item.get('price'))
      query.set('price', price);
      query.set('count', count);
      query.set('brokerage',brokerage); //佣金总额
      let externalGoodsObj = AV.Object.createWithoutData('External_goods', item.id);
      query.set('externalGoodsOId', item.id);
      query.set('externalGoodsObj', externalGoodsObj);
      query.set('classify', classify);
      query.set('isVip', isVip);
      query.set('freight', freight);
      query.set('score', score);
      query.set('presentScore', presentScore);
      query.set('superiorMoney', superiorMoney);
      query.set('superiorSuperiorMoney', superiorSuperiorMoney);
      query.set('superiorSuperiorSuperiorMoney', superiorSuperiorSuperiorMoney);
      query.set('ancestorsMoney', ancestorsMoney);
      query.set('superiorScore', superiorScore);
      query.set('superiorSuperiorScore', superiorSuperiorScore);
      query.set('ancestorsScore', ancestorsScore);
      if (goodsTypePId != null && goodsTypePId != '') {
        let goodsTypePObj = AV.Object.createWithoutData('Shop_good_type', goodsTypePId);
        query.set('shopGoodsTypeParentOId', goodsTypePId);
        query.set('shopGoodsTypeParentObj', goodsTypePObj);
        query.set('shopGoodsTypeOId', goodsTypeOId);
        query.set('shopGoodsTypeObj', goodsTypeObj);
      } else {
        query.set('shopGoodsTypeParentOId', goodsTypeOId);
        query.set('shopGoodsTypeParentObj', goodsTypeObj);
      }
      objs.push(query)
    }
    return AV.Object.saveAll(objs).then(success => {
      // console.log("success")
      return success
    }, reject => {
      console.log(reject);
      return reject
    })
  }
}

function getExternalGoodsInfoForBatch (goodsOIds){
  var query = new AV.Query('External_goods');
  query.containedIn('objectId', goodsOIds);
  return query.find().then(result=>{
      return result
  }).catch(error=>{
      console.log('getExternalGoodsInfoForBatch',error)
  })
}

exports.deleteShopIntergation = deleteShopIntergation;

async function deleteShopIntergation(req, callback) {
    let ids = req.body.ids;
    let objects = [];
    for (let objectId of ids) {
        let scoreShop = AV.Object.createWithoutData('Score_shop_goods', objectId);
        scoreShop.set('status',-1)
        objects.push(scoreShop);
    }
    AV.Object.saveAll(objects).then(resolve => {
        callback(null, "10001")
    }, reject => {
        callback(reject, "10002")
    })
    // AV.Object.destroyAll(objects).then(resolve => {
    //   callback(null, "10001")
    // }, reject => {
    //   callback(reject, "10002")
    // })
}

exports.deleShopGoodRecommend = deleShopGoodRecommend;

function deleShopGoodRecommend(req, callback) {
    let ids = req.body.ids;
    let objects = [];
    for (let objectId of ids) {
        let shopRecommend = AV.Object.createWithoutData('Shop_good_recommend', objectId);
        shopRecommend.set('status', '-1');
        objects.push(shopRecommend);
    }
    AV.Object.saveAll(objects).then(resolve => {
        callback(null, "10001")
    }, reject => {
        callback(reject, "10002")
    })
}

exports.selectScoreShopGoods = selectScoreShopGoods;

function selectScoreShopGoods(objectId) {
    if (objectId != null && objectId != '') {
        let query = new AV.Query('Score_shop_goods');
        query.include('shopGoodsTypeParentObj');
        query.include('shopGoodsTypeObj');
        return query.get(objectId).then(function (item) {
            let temObj = {};
            temObj["objectId"] = item.id;
            temObj["price"] = item.get('price');
            temObj["isVip"] = item.get('isVip')?item.get('isVip'):0;
            temObj["freight"] = item.get('freight');
            temObj["score"] = item.get('score');
            temObj["count"] = item.get('count');
            temObj["brokerage"] = item.get('brokerage')?item.get('brokerage'):0;
            temObj["presentScore"] = item.get('presentScore');
            temObj["superiorMoney"] = item.get('superiorMoney');
            temObj["superiorSuperiorMoney"] = item.get('superiorSuperiorMoney');
            temObj["superiorSuperiorSuperiorMoney"] = item.get('superiorSuperiorSuperiorMoney');
            temObj["ancestorsMoney"] = item.get('ancestorsMoney');
            temObj["superiorScore"] = item.get('superiorScore');
            temObj["superiorSuperiorScore"] = item.get('superiorSuperiorScore');
            // temObj["superiorSuperiorSuperiorScore"] = item.get('superiorSuperiorSuperiorScore');
            temObj["ancestorsScore"] = item.get('ancestorsScore');
            let parentGoodsTypeName = item.get('shopGoodsTypeParentObj') ? item.get('shopGoodsTypeParentObj').get('name') : '';
            let goodsTypeName = item.get('shopGoodsTypeObj') ? item.get('shopGoodsTypeObj').get('name') : '';
            if (parentGoodsTypeName != ''){
                temObj['goodsType'] = parentGoodsTypeName + '-' + goodsTypeName;
            } else {
                temObj['goodsType'] = goodsTypeName;
            }
            if (item.get('shopGoodsTypeOId')){
              temObj['shopGoodsTypeOId'] = item.get('shopGoodsTypeOId')
              temObj['shopGoodsTypeParentOId'] = item.get('shopGoodsTypeParentOId')
            } else {
              temObj['shopGoodsTypeOId'] = item.get('shopGoodsTypeParentOId')
            }
            temObj.groupPrice = item.get('groupPrice');
            temObj.groupScore = item.get('groupScore');
            temObj.limitNum= item.get('limitNum');
            temObj.groupPeopleNum = item.get('groupPeopleNum');
            temObj.minGroupPeopleNum = item.get('minGroupPeopleNum');
            temObj.groupDuration = Number(item.get('groupDuration'));
            temObj.groupStartTime = moment(item.get('groupStartTime')).format('YYYY-MM-DD HH:mm:ss');
            temObj.groupEndTime = moment(item.get('groupEndTime')).format('YYYY-MM-DD HH:mm:ss');

            return temObj
        }).catch(error=>{
            console.log(error)
        })
    }
}

exports.editScoreGoodsShop = editScoreGoodsShop;

function editScoreGoodsShop(data) {
    let objectId = data.objectId
    let price = Number(data.price);
    let score = Number(data.score);
    let freight = Number(data.freight);
    let count = Number(data.count);
    let brokerage = Number(data.brokerage);
    let presentScore = Number(data.presentScore);
    let superiorMoney = Number(data.superiorMoney);
    let superiorSuperiorMoney = Number(data.superiorSuperiorMoney);
    let superiorSuperiorSuperiorMoney = Number(data.superiorSuperiorSuperiorMoney);
    let ancestorsMoney = Number(data.ancestorsMoney);
    let superiorScore = Number(data.superiorScore);
    let superiorSuperiorScore = Number(data.superiorSuperiorScore);
    // let superiorSuperiorSuperiorScore = Number(data.superiorSuperiorSuperiorScore);
    let ancestorsScore = Number(data.ancestorsScore);
    let isVip = Number(data.isVip);
    let goodsTypeOId = data.goodsTypeOId;
    let goodsTypePId = data.goodsTypePId;
    var goodsTypeObj = AV.Object.createWithoutData('Shop_good_type', goodsTypeOId);
    let updateScoreShop = AV.Object.createWithoutData("Score_shop_goods", objectId);
    updateScoreShop.set('price', price);
    updateScoreShop.set('isVip', isVip);
    updateScoreShop.set('score', score);
    updateScoreShop.set('freight', freight);
    updateScoreShop.set('count', count);
    updateScoreShop.set('brokerage', brokerage); //佣金总额
    updateScoreShop.set('presentScore', presentScore);
    updateScoreShop.set('superiorMoney', superiorMoney);
    updateScoreShop.set('superiorSuperiorMoney', superiorSuperiorMoney);
    updateScoreShop.set('superiorSuperiorSuperiorMoney', superiorSuperiorSuperiorMoney);
    updateScoreShop.set('ancestorsMoney', ancestorsMoney);
    updateScoreShop.set('superiorScore', superiorScore);
    updateScoreShop.set('superiorSuperiorScore', superiorSuperiorScore);
    // updateScoreShop.set('superiorSuperiorSuperiorScore', superiorSuperiorSuperiorScore);
    updateScoreShop.set('ancestorsScore', ancestorsScore);
    updateScoreShop.set('shopGoodsTypeOId', goodsTypeOId);
    updateScoreShop.set('shopGoodsTypeObj', goodsTypeObj);
    // if (goodsTypePId != null && goodsTypePId != '') {
    //   let goodsTypePObj = AV.Object.createWithoutData('Shop_good_type', goodsTypePId);
    //   updateScoreShop.set('shopGoodsTypeParentOId', goodsTypePId);
    //   updateScoreShop.set('shopGoodsTypeParentObj', goodsTypePObj);
    // } else {
    //   updateScoreShop.unset('shopGoodsTypeParentOId')
    //   updateScoreShop.unset('shopGoodsTypeParentObj');
    // }
    if (goodsTypePId != null && goodsTypePId != '') {
        let goodsTypePObj = AV.Object.createWithoutData('Shop_good_type', goodsTypePId);
        updateScoreShop.set('shopGoodsTypeParentOId', goodsTypePId);
        updateScoreShop.set('shopGoodsTypeParentObj', goodsTypePObj);
        updateScoreShop.set('shopGoodsTypeOId', goodsTypeOId);
        updateScoreShop.set('shopGoodsTypeObj', goodsTypeObj);
    } else {
        updateScoreShop.set('shopGoodsTypeParentOId', goodsTypeOId);
        updateScoreShop.set('shopGoodsTypeParentObj', goodsTypeObj);
        updateScoreShop.unset('shopGoodsTypeOId')
        updateScoreShop.unset('shopGoodsTypeObj');
    }
    return updateScoreShop.save().then(function (result) {
        return result;
    })
}

exports.findShopRecommend = findShopRecommend;

function findShopRecommend(page, num) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    let query = new AV.Query('Shop_good_recommend');
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shopGoodsObj');
    query.include('shopGoodsObj.shopObj');
    query.descending('createdAt');

    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            let qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let shopGoodsVal = item.get("shopGoodsObj");
                let temObj = {};
                temObj["id"] = item.get("objectId");
                temObj["objectId"] = shopGoodsVal ? shopGoodsVal.get('objectId') : '';
                temObj["title"] = shopGoodsVal ? shopGoodsVal.get('title') : '';
                temObj["shopIcon"] = shopGoodsVal ? qn + shopGoodsVal.get('picName') : '';
                temObj["name"] = shopGoodsVal ? (shopGoodsVal.get("shopObj") ? shopGoodsVal.get("shopObj").get("name") : '') : '';
                temObj["status"] = item.get("status");
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })

}

exports.addShopGoodsRecommend = addShopGoodsRecommend;

function addShopGoodsRecommend(shopGoodsOId) {
    if (shopGoodsOId != '' && shopGoodsOId != null) {
        let shopGoodsObj = AV.Object.createWithoutData('Shop_goods', shopGoodsOId);
        let ShopRecommend = AV.Object.extend('Shop_good_recommend');
        let query = new ShopRecommend();
        query.set('shopGoodsOId', shopGoodsOId);
        query.set('shopGoodsObj', shopGoodsObj);
        query.set('status', '0');
        return query.save().then(function (result) {
            return result;
        })
    }
}

exports.selShopGoodRecommend = selShopGoodRecommend;

function selShopGoodRecommend(objectId) {

    if (objectId != null && objectId != '') {
        let query = new AV.Query('Shop_good_recommend');
        return query.get(objectId).then(function (result) {
            let obj = {};
            let shopGoodsObj = result.get("shopGoodsObj");
            obj.status = result.get("status");
            return obj;
        })
    }
}

exports.updShopGoodRecommend = updShopGoodRecommend;

function updShopGoodRecommend(objectId, status) {
    let query = AV.Object.createWithoutData('Shop_good_recommend', objectId);
    query.set('status', status);
    return query.save().then(function (result) {
        return result
    })
}

exports.androidVersion = androidVersion;

async function androidVersion(objectId, versionName, versionNo, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Version');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    if (versionNo != "" && versionNo != undefined && versionNo != null) {
        query.equalTo("versionNo", versionNo);
    }
    if (versionName != "" && versionName != undefined && versionName != null) {
        query.contains("versionName", versionName);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["versionNo"] = item.get("versionNo");
                temObj["content"] = item.get("content");
                temObj["downUrl"] = item.get("downUrl");
                temObj["desUrl"] = item.get("desUrl");
                temObj["versionName"] = item.get("versionName");
                temObj["creater"] = item.get("creater");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

// exports.updateAndroid=updateAndroid;
// function updateAndroid(req,callback) {
//     var objectId = req.params.objectId;
//     // 修改属性
//     if(objectId!=""&&objectId!=undefined&&objectId!=null){
//         var Ver = AV.Object.createWithoutData('Version',objectId);
//     }else{
//         var Vers = AV.Object.extend('Version');
//         var Ver = new Vers();
//     }
//     Ver.set('versionNo', req.params.versionNo);
//     Ver.set('versionName', req.params.versionName);
//     Ver.set('content',req.params.content);
//     Ver.set('downUrl',req.params.downUrl);
//     Ver.set('desUrl',req.params.desUrl);
//     Ver.set('creater',req.params.creater);
//     // 保存到云端
//     Ver.save().then(function (success) {
//             callback(null,"10001");
//         },function (error) {
//             console.log(error);
//             callback(error,"10002")
//         }
//     )
// }

// exports.updateAndroid=updateAndroid;
// async function updateAndroid(req,callback) {
//     var form = new multiparty.Form();
//     form.parse(req,async function (err,fields,files) {
//         var versionNo = fields.versionNo?fields.versionNo[0]:null;
//         var versionName = fields.versionName?fields.versionName[0]:null;
//         var objectId = fields.objectId?fields.objectId[0]:null;
//         var creater = fields.creater?fields.creater[0]:null;
//         var content = fields.content?fields.content[0]:null;
//         var apk =   files.Fdata[0].size?files.Fdata[0]:null;
//         var key = versionNo+".apk";
//         if (objectId!=""&&objectId!=null){
//             var Ver = AV.Object.createWithoutData("Version",objectId)
//         }else {
//             var Vers = AV.Object.extend("Version");
//             var Ver = new Vers();
//         }
//         if (apk!=""&&apk!=null){
//             var status = await uploadApk(apk.path,key);
//             key = "http://7xiuo5.com1.z0.glb.clouddn.com/"+key
//             if(status==200){
//                 Ver.set("downUrl",key);
//             }else {
//                 return callback("error","10002")
//             }
//         }
//         Ver.set("versionNo",versionNo);
//         Ver.set("versionName",versionName);
//         Ver.set("creater",creater);
//         Ver.set("content",content);
//         Ver.save().then(function (shop) {
//             callback(null,"10001");
//         })
//     })
// }


exports.updateAndroid = updateAndroid;

async function updateAndroid(req, callback) {
    var objectId = req.params.objectId;
    if (objectId != "" && objectId != null) {
        var Ver = AV.Object.createWithoutData("Version", objectId)
    } else {
        var Vers = AV.Object.extend("Version");
        var Ver = new Vers();
    }
    Ver.set("versionNo", req.params.versionNo);
    Ver.set("versionName", req.params.versionName);
    Ver.set("creater", req.params.creater);
    Ver.set("desUrl", req.params.desUrl);
    Ver.set("content", req.params.content);
    Ver.set("downUrl", req.params.downUrl);
    Ver.save().then(function (ver) {
        callback(null, "10001");
    })
}


exports.updateIos = updateIos;

function updateIos(req, callback) {
    var objectId = req.params.objectId;
    var Ver = AV.Object.createWithoutData('Ios_version', objectId);
    Ver.set('version', req.params.version);
    Ver.save().then(function (success) {
            callback(null, "10001");
        }, function (error) {
            console.log(error);
            callback(error, "10002")
        }
    )
}

exports.receiveAddress = receiveAddress;

async function receiveAddress(userOId, objectId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_receive_address');
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["address"] = item.get("address");
                temObj["isDefault"] = item.get("isDefault");
                temObj["name"] = item.get("name");
                temObj["city"] = item.get("city");
                temObj["tel"] = item.get("tel");
                temObj["province"] = item.get("province");
                temObj["oldUserOId"] = item.get("oldUserOId");
                temObj["userOId"] = item.get("userOId");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.updateUserAddress = updateUserAddress;

async function updateUserAddress(req, callback) {
    var objectId = req.params.objectId;
    var isDefault = req.params.isDefault;
    var userOId = req.params.userOId;
    if (objectId != "" && objectId != null) {
        var Ver = AV.Object.createWithoutData("Shop_receive_address", objectId)
    } else {
        var Vers = AV.Object.extend("Shop_receive_address");
        var Ver = new Vers();
    }
    if (isDefault == 1) {
        await changeDefaultAddress(userOId);
    }
    Ver.set('userOId', userOId);
    Ver.set("isDefault", isDefault);
    Ver.set("address", req.params.address);
    Ver.set("name", req.params.name);
    Ver.set("city", req.params.city);
    Ver.set("tel", req.params.tel);
    Ver.set("province", req.params.province);
    Ver.set("userOId", req.params.userOId);
    Ver.save().then(function (ver) {
        callback(null, "10001");
    })
}

function changeDefaultAddress(userOId) {
    let query = new AV.Query("Shop_receive_address");
    query.equalTo('userOId', userOId)
    query.equalTo('isDefault', "1")
    return query.find().then((address) => {
        if (address == "" || address == null) {
            return
        }
        address.forEach((item) => {
            item.set('isDefault', "0")
        })
        AV.Object.saveAll(address).then((result) => {
            return
        })
    })
}

exports.userShopAccount = userShopAccount;

async function userShopAccount(userOId, objectId, nickName, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_account');
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        let Users = await findUser(nickName);
        query.containedIn("userOId", Users);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('userObj');
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["userOId"] = item.get('userOId');
                var frozenMoney = item.get('frozenMoney');//冻结金额
                var withdrawFrozenMoney = item.get('withdrawFrozenMoney');
                var currentMoney = item.get('currentMoney');
                var withdrawMoney = item.get('withdrawMoney');//提现金额
                var makeMoney = (frozenMoney + currentMoney + withdrawMoney).toFixed(2);
                var walletMoney = (frozenMoney + currentMoney).toFixed(2);
                temObj["frozenMoney"] = frozenMoney;
                temObj["withdrawFrozenMoney"] = withdrawFrozenMoney;
                temObj["currentMoney"] = currentMoney;
                temObj["withdrawMoney"] = withdrawMoney;
                temObj["makeMoney"] = makeMoney;
                temObj["walletMoney"] = walletMoney;
                temObj["userAvatar"] = item.get('userObj').get("userAvatar") ? item.get('userObj').get("userAvatar").url() : "";
                temObj["mobilePhoneNumber"] = item.get('userObj').get("mobilePhoneNumber");
                temObj["live_authority"] = item.get('userObj').get("live_authority");
                temObj["verify_authority"] = item.get('userObj').get("verify_authority");
                temObj["authData"] = item.get('userObj').get("authData");
                temObj["nickName"] = item.get('userObj').get("nickName");
                temObj["phoneRegVerify"] = item.get('userObj').get("phoneRegVerify");
                temObj["status"] = item.get('userObj').get("status");
                temObj["province"] = item.get('userObj').get("province");
                temObj["city"] = item.get('userObj').get("city");
                temObj["userType"] = item.get('userObj').get("userType");
                temObj["signature"] = item.get('userObj').get("signature");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.userFriends = userFriends;

async function userFriends(userOId, objectId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('FriendRelation');
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo("userOId", userOId);
    }
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId);
    }

    query.limit(num);
    query.skip((page - 1) * num);
    query.include('friendObj');
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["friendOId"] = item.get('friendOId');
                temObj["sex"] = item.get('friendObj').get("sex");
                temObj["uid"] = item.get('friendObj').get("uid");
                temObj["username"] = item.get('friendObj').get("username");
                temObj["regisFrom"] = item.get('friendObj').get("regisFrom");
                temObj["gender"] = item.get('friendObj').get("userAvatar") ? item.get('friendObj').get("userAvatar").url() : "";
                temObj["mobilePhoneNumber"] = item.get('friendObj').get("mobilePhoneNumber");
                temObj["live_authority"] = item.get('friendObj').get("live_authority");
                temObj["verify_authority"] = item.get('friendObj').get("verify_authority");
                temObj["authData"] = item.get('friendObj').get("authData");
                temObj["nickName"] = item.get('friendObj').get("nickName");
                temObj["phoneRegVerify"] = item.get('friendObj').get("phoneRegVerify");
                temObj["status"] = item.get('friendObj').get("status");
                temObj["address"] = item.get('friendObj').get("province") + item.get('friendObj').get("city");
                temObj["province"] = item.get('friendObj').get("province");
                temObj["city"] = item.get('friendObj').get("city");
                temObj["qrCode"] = item.get('friendObj').get("qrCode") ? item.get('friendObj').get("qrCode").url() : "";
                temObj["userType"] = item.get('friendObj').get("userType");
                temObj["signature"] = item.get('friendObj').get("signature");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.AuthImg = class AuthImg {
    constructor(userInfo, authClass) {
        var authPath = {
            newWeChat: process.cwd() + '/public/image/newAuth.png',
            taiZiFei: process.cwd() + '/public/image/taiZiFei.png',
        }
        var fillTextPoistion = {
            newWeChat: {
                authCode: {left: 315, top: 406},
                name: {left: 210, top: 502},
                idCard: {left: 232, top: 543},
                weChat: {left: 208, top: 586},
                telephone: {left: 208, top: 626},
                levelName: {left: 232, top: 996},
                teamLeader: {left: 186, top: 1038},
                resultTime: {left: 236, top: 1120},
            },
            taiZiFei: {
                authCode: {left: 315, top: 406},
                name: {left: 210, top: 484},
                idCard: {left: 232, top: 525},
                weChat: {left: 208, top: 566},
                telephone: {left: 208, top: 608},
                levelName: {left: 232, top: 1018},
                teamLeader: {left: 186, top: 1061},
                resultTime: {left: 236, top: 1183},
            }
        }
        this.userInfo = userInfo;
        this.filePath = process.cwd() + '/public/image/newAuth.png';
        this.chapterPath = process.cwd() + '/public/image/chapter.png';
        this.key = uuid.v1().replace(/-/g, "") + ".png";
        this.fontPath = process.cwd() + '/public/font/lantinhj.ttf'
        if (authClass == 'taiZiFei') {
            this.filePath = authPath.taiZiFei;
            this.fileText = fillTextPoistion.taiZiFei;
        } else if (authClass == 'newWeChat') {
            this.filePath = authPath.newWeChat;
            this.fileText = fillTextPoistion.newWeChat;
        }
    }

    upload(cb) {
        var imagePath = process.cwd() + "\\" + this.key;
        var chapterPath = this.chapterPath;
        var objectId = this.userInfo.objectId;
        var key = this.key
        imageMagick(this.filePath)
            .font(this.fontPath)
            .fontSize(21)
            .fill('#222222')
            .drawText(this.fileText.authCode.left, this.fileText.authCode.top, this.userInfo.authCode)
            .drawText(this.fileText.name.left, this.fileText.name.top, this.userInfo.name)
            .drawText(this.fileText.idCard.left, this.fileText.idCard.top, this.userInfo.idCard)
            .drawText(this.fileText.weChat.left, this.fileText.weChat.top, this.userInfo.weChat)
            .drawText(this.fileText.telephone.left, this.fileText.telephone.top, this.userInfo.telephone)
            .drawText(this.fileText.levelName.left, this.fileText.levelName.top, this.userInfo.levelName)
            .drawText(this.fileText.teamLeader.left, this.fileText.teamLeader.top, this.userInfo.teamLeader)
            .drawText(this.fileText.resultTime.left, this.fileText.resultTime.top, this.userInfo.resultTime)
            .write(imagePath, function (err) {
                if (!err) {
                    imageMagick()
                        .in('-page', '+0+0')
                        .in(imagePath)
                        .in('-page', '+468+1070') // location of smallIcon.jpg is x,y -> 10, 20
                        .in(chapterPath)
                        .mosaic()
                        .write(imagePath, function (err) {
                            if (!err) {
                                qn.uploadImg(imagePath, key, function (error, rs) {
                                    if (rs == '200') {
                                        fs.unlinkSync(imagePath);
                                        updateUserAuthImage(objectId, key, function (error, rs) {

                                            cb(null, "10000");
                                        });
                                    } else {
                                        cb(error, "10002");
                                    }
                                })
                            }
                            else {
                                console.log(err)
                            }
                            ;
                        });
                } else {
                    console.log(err.message || "出错了！");
                }
            });
    };
}

exports.shopTribeGoods = shopTribeGoods;

async function shopTribeGoods(objectId, tribeOId, title, goodsOId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_tribe_goods');
    // if (tribeOId != "" && tribeOId != undefined && tribeOId != null) {
    //     query.equalTo("tribeOId", tribeOId);
    // }
    if (goodsOId != "" && goodsOId != undefined && goodsOId != null) {
        query.equalTo("goodOId", goodsOId);
    }
    if (title != "" && title != undefined && title != null) {
        let goods = await findGoods(title);
        query.containedIn("goodOId", goods);
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('goodObj');
    query.descending("createdAt");
    query.find().then(function (result) {
        query.count().then(function (count) {
            var obj = {};
            var data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.id;
                temObj["goodsOId"] = item.get('goodOId');
                temObj["title"] = item.get('goodObj').get("title") ? item.get('goodObj').get("title") : "";
                temObj["picName"] = item.get('goodObj').get("picName");
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(null, obj);
        })
    })
};

exports.liveBindGoods = liveBindGoods;

async function liveBindGoods(objectId, page, num, callback) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Live_room');
    if (objectId != "" && objectId != undefined && objectId != null) {
        query.equalTo("objectId", objectId)
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('goods');
    query.first().then(function (result) {
        var obj = {};
        var data = [];
        if (result.get("goods")) {
            var count = result.get("goods").length;
            for (let item of result.get("goods")) {
                console.log("aaa")
                var temObj = {};
                temObj["goodsOId"] = item.get('objectId');
                temObj["title"] = item.get("title");
                temObj["picName"] = item.get("picName");
                temObj["updatedAt"] = moment(item.get("updatedAt")).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(item.get("createdAt")).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
        }
        console.log(data)
        obj.data = data;
        obj.total = count;
        callback(null, obj);

    })
};

exports.getQuestion = getQuestion;

async function getQuestion(params) {
    let page = params.page
    let pageSize = params.pageSize
    let type = params.type
    let title = params.title
    let url = params.url

    if (page == '' || page == undefined || page == null) {
        page = 0;
    } else {
        page = parseInt(page);
    }
    if (pageSize == '' || pageSize == undefined || pageSize == null) {
        pageSize = 20
    } else {
        pageSize = parseInt(pageSize)
    }
    let query = new AV.Query('Question');
    if (title != "" && title != undefined && title != null) {
        query.contains("title", title);
    }
    if (type != "" && type != undefined && type != null) {
        query.equalTo("type", type);
    }
    if (url != "" && url != undefined && url != null) {
        query.contains("url", url);
    }
    query.limit(pageSize);
    query.skip((page - 1) * pageSize);
    query.descending("createdAt");
    return query.find().then(function (results) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            results.forEach(item => {
                let temObj = {};
                temObj.objectId = item.get('objectId')
                temObj.type = item.get('type')
                temObj.title = item.get('title')
                temObj.url = item.get('url')
                temObj.createdAt = moment(item.get("createdAt")).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            })
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.questionAdd = questionAdd;

async function questionAdd(params) {
    let type = params.type
    let title = params.title
    let url = params.url
    let Question = AV.Object.extend('Question');
    let question = new Question();
    question.set('type', type);
    question.set('title', title);
    question.set('url', url);
    return question.save().then(function (result) {
        if (result) {
            return result.id
        } else {
            console.log('问卷调查添加失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.questionEdit = questionEdit;

function questionEdit(objectId) {
    let query = new AV.Query('Question');
    return query.get(objectId).then(function (result) {
        return result;
    }, function (error) {
        console.log(error);
    })
}

exports.questionUpdate = questionUpdate;

async function questionUpdate(params) {
    let objectId = params.objectId;
    let type = params.type;
    let title = params.title;
    let url = params.url;
    var question = AV.Object.createWithoutData("Question", objectId)
    question.set('type', type);
    question.set('title', title);
    question.set('url', url);
    return question.save().then(result => {
        // console.log(result)
        if (result) {
            return result
        } else {
            console.log('问卷调查添加失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.questionRemove = questionRemove;

async function questionRemove(objectId) {
    // console.log(objectId)
    var question = AV.Object.createWithoutData('Question', objectId);
    return question.destroy().then(result => {
        // console.log(result)
        if (result) {
            return result.id
        }

    }).catch(error => {
        console.log(error)
    })
}

exports.getGoodsTribeCorrelation = getGoodsTribeCorrelation;

function getGoodsTribeCorrelation(data) {
    var page = data.page
    var num = data.num
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Shop_goods_tribe');
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('tribeObj')
    query.include('shopGoodsObj')
    query.descending("createAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            // console.log(result)
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["shopGoodsOId"] = item.get("shopGoodsOId");
                temObj["goodsName"] = item.get("shopGoodsObj").get('title');
                temObj["tribeOid"] = item.get("tribeOid");
                temObj["tribeName"] = item.get("tribeObj").get('name');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(err => {
            console.log(err)
        })
    }).catch(error => {
        console.log(error)
    })
}

exports.goodsTribeCorrelationAdd = goodsTribeCorrelationAdd;

async function goodsTribeCorrelationAdd(params) {
    let shopGoodsOId = params.shopGoodsOId
    if (shopGoodsOId && shopGoodsOId != '' && shopGoodsOId.length > 0) {
        var shopGoodsObj = AV.Object.createWithoutData('Shop_goods', shopGoodsOId);
    } else {
        console.log('商品部落关联添加时未找到商品ID!')
        return false
    }
    let tribeOid = params.tribeOId
    if (tribeOid && tribeOid != '' && tribeOid.length > 0) {
        var tribeObj = AV.Object.createWithoutData('Tribe', tribeOid);
    } else {
        console.log('商品部落关联添加时未找到部落ID!')
        return false
    }
    let ShopGoodsTribe = AV.Object.extend('Shop_goods_tribe');
    let shopGoodsTribe = new ShopGoodsTribe();
    shopGoodsTribe.set('shopGoodsOId', shopGoodsOId);
    shopGoodsTribe.set('shopGoodsObj', shopGoodsObj);
    shopGoodsTribe.set('tribeOid', tribeOid);
    shopGoodsTribe.set('tribeObj', tribeObj);
    return shopGoodsTribe.save().then(function (result) {
        // console.log(result)
        if (result) {
            return result.id
        } else {
            console.log('商品部落关联失败！')
        }
    }).catch(error => {
        console.log(error)
    })
}

exports.goodsTribeCorrelationDel = goodsTribeCorrelationDel;

async function goodsTribeCorrelationDel(objectId) {
    if (objectId) {
        var question = AV.Object.createWithoutData('Shop_goods_tribe', objectId);
        return question.destroy().then(result => {
            if (result) {
                return result.id
            }
        }).catch(error => {
            console.log(error)
        })
    } else {
        console.log('未获取到商品部落关联ID！')
    }
}


exports.getDeviceLiveUrlForIp = getDeviceLiveUrlForIp;

async function getDeviceLiveUrlForIp(rtmpUrl) {
    let options = {
        method: 'get',
        uri: 'http://pili-ipswitch.qiniuapi.com/v1/query/publish?stream=http://pili-publish.141cn.com/&clientIP=58.132.169.112',
        headers: {
            'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }
    }
    return rp(options).then(result => {
        // console.log(result,'-=--=--=-=-=')
        var data = []
        JSON.parse(result).items.map(item => {
            let obj = {}
            obj.rtmpUrlForIp = rtmpUrl.replace('pili-publish.141cn.com', item.ip)
            data.push(obj)
        })
        // console.log(data)
        return data
    }).catch(error => {
        console.log(error, '-=-=--=--=')
        return null
        // return error
    })
}

exports.getUserInviteFriends = getUserInviteFriends;

function getUserInviteFriends(data) {
    var page = data.page
    var num = data.num
    let nickName = data.nickName
    let mobilePhoneNumber = data.mobilePhoneNumber
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Apprentice');
    if (nickName != "" && nickName != undefined && nickName != null) {
        var userQueryNickName = new AV.Query('_User');
        userQueryNickName.contains('nickName', nickName);
        query.matchesQuery('userObj', userQueryNickName);
    }
    if (mobilePhoneNumber != "" && mobilePhoneNumber != undefined && mobilePhoneNumber != null) {
        var userQueryMobilePhoneNumber = new AV.Query('_User');
        userQueryMobilePhoneNumber.contains('mobilePhoneNumber', mobilePhoneNumber);
        query.matchesQuery('userObj', userQueryMobilePhoneNumber);
    }

    query.limit(num);
    query.skip((page - 1) * num);
    query.include('inviterObj')
    query.include('userObj')
    query.descending("createAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["isScoreParent"] = item.get("isScoreParent") ? item.get("isScoreParent") : ''; //邀请积分是否已支付 1为已领 空为已支付
                temObj["inviterOId"] = item.get("inviterOId");
                temObj["inviterNickName"] = item.get("inviterObj").get('nickName');
                temObj["inviterInviteCode"] = item.get("inviterObj").get('inviteCode');
                temObj["userOId"] = item.get("userOId");
                temObj["userNickName"] = item.get("userObj").get('nickName');
                temObj["mobilePhoneNumber"] = item.get("userObj").get('mobilePhoneNumber');
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                // temObj["inviterSteps"] = item.get("inviterSteps");
                // temObj["scoreDay"] = item.get("scoreDay"); //当天积分收入
                // temObj["income"] = item.get("income"); //邀请积分收入
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(err => {
            console.log(err)
        })
    }).catch(error => {
        console.log(error)
    })
}

exports.userInviteFriendsDel = userInviteFriendsDel;

async function userInviteFriendsDel(objectId) {
    if (objectId) {
        var question = AV.Object.createWithoutData('Apprentice', objectId);
        return question.destroy().then(result => {
            if (result) {
                return result.id
            }
        }).catch(error => {
            console.log(error)
        })
    } else {
        console.log('未获取到用户邀请ID！')
    }
}

exports.getSystemSendScoreList = getSystemSendScoreList;

function getSystemSendScoreList(data) {
    var page = data.page
    var num = data.num
    let userOId = data.userOId
    let nickName = data.nickName
    let mobilePhoneNumber = data.mobilePhoneNumber

    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    let query = new AV.Query('Tribe_score');
    if (userOId != "" && userOId != undefined && userOId != null) {
        query.equalTo('userOId', userOId)
        console.log('userOId:', userOId)
    }
    if (nickName != "" && nickName != undefined && nickName != null) {
        var userQueryNickName = new AV.Query('_User');
        userQueryNickName.contains('nickName', nickName);
        query.matchesQuery('userObj', userQueryNickName);
        console.log('nickName:', nickName)
    }
    if (mobilePhoneNumber != "" && mobilePhoneNumber != undefined && mobilePhoneNumber != null) {
        var userQueryMobilePhoneNumber = new AV.Query('_User');
        userQueryMobilePhoneNumber.contains('mobilePhoneNumber', mobilePhoneNumber);
        query.matchesQuery('userObj', userQueryMobilePhoneNumber);
        console.log('mobilePhoneNumber:', mobilePhoneNumber)
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('userObj')
    query.descending("createAt");
    query.equalTo('scoreType', 'SYSTEM_REWARD')
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["userOId"] = item.get("userOId");
                temObj["userNickName"] = item.get("userObj").get('nickName');
                temObj["mobilePhoneNumber"] = item.get("userObj").get('mobilePhoneNumber');
                temObj["type"] = item.get("type");
                temObj["score"] = item.get("score");
                temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(err => {
            console.log(err)
        })
    }).catch(error => {
        console.log(error)
    })
}

exports.systemSendScoreAdd = systemSendScoreAdd;

async function systemSendScoreAdd(params) {
    let userOId = params.userOId
    let score = Number(params.score)
    let scoreType = 'SYSTEM_REWARD'
    let type = '系统奖励积分'
    let userObj = AV.Object.createWithoutData('_User', userOId);
    userObj.increment('score', score)
    return userObj.save().then(user => {
        if (user) {
            let Tribe_score = AV.Object.extend('Tribe_score');
            let tribe_score = new Tribe_score();
            tribe_score.set('userOId', userOId);
            tribe_score.set('userObj', user);
            tribe_score.set('score', score);
            tribe_score.set('scoreType', scoreType);
            tribe_score.set('type', type);
            return tribe_score.save().then(function (result) {
                // console.log(result)
                if (result) {
                    return result.id
                } else {
                    console.log('系统发分失败！')
                }
            }).catch(error => {
                console.log(error)
            })
        } else {
            console.log('操作用户积分失败！')
        }
    }).catch(errs => {
        console.log(errs)
    })
}

exports.systemSendScoreDel = systemSendScoreDel;

async function systemSendScoreDel(data) {
    let objectId = data.objectId
    let userOId = data.userOId
    let score = 0 - Number(data.score)
    let userObj = AV.Object.createWithoutData('_User', userOId);
    userObj.increment('score', score)
    return userObj.save().then(user => {
        if (user) {
            let tribeScore = AV.Object.createWithoutData('Tribe_score', objectId);
            return tribeScore.destroy().then(result => {
                if (result) {
                    return result.id
                }
            }).catch(error => {
                console.log(error)
            })
        } else {
            console.log('操作用户积分失败！')
        }
    }).catch(err => {
        console.log(err)
    })
}


exports.scoreShopGoodSelect = scoreShopGoodSelect;

function scoreShopGoodSelect(data) {
    let objectId = data.objectId
    let name = data.name
    let page = data.page
    let num = data.num
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    console.log(data)
    let query = new AV.Query('Score_shop_goods');
    if (objectId != '' && objectId != undefined && objectId != null) {
        query.equalTo('objectId', objectId);
    }
    if (name != '' && name != undefined && name != null) {
        let shopGoods = new AV.Query('Shop_goods');
        shopGoods.contains('title', name);
        query.matchesQuery('shopGoodsObj', shopGoods);
    }
    query.notEqualTo('status',-1)

    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shopGoodsObj')
    query.include('externalGoodsObj')
    // query.exists('shopGoodsObj')
    query.descending("createdAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            var obj = {};
            var data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get('objectId');
                if (item.get('classify') == 2){
                  temObj["title"] = item.get('externalGoodsObj')?item.get('externalGoodsObj').get("sourceGoodsName"):"";
                  temObj["shopIcon"] = item.get('externalGoodsObj') ? item.get('externalGoodsObj').get("sourceGoodsIcon") : '';
                } else {
                  temObj["title"] = item.get('shopGoodsObj')?item.get('shopGoodsObj').get("title"):"";
                  temObj["shopIcon"] = item.get('shopGoodsObj').get("picName") ? qn + item.get('shopGoodsObj').get("picName") : '';
                }
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}
exports.scoreShopGoodSelectNoGroup = scoreShopGoodSelectNoGroup;

function scoreShopGoodSelectNoGroup(data) {
    let objectId = data.objectId
    let name = data.name
    let page = data.page
    let num = data.num
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20
    } else {
        num = parseInt(num)
    }
    console.log(data)
    let query = new AV.Query('Score_shop_goods');
    if (objectId != '' && objectId != undefined && objectId != null) {
        query.equalTo('objectId', objectId);
    }
    if (name != '' && name != undefined && name != null) {
        let shopGoods = new AV.Query('Shop_goods');
        shopGoods.contains('title', name);
        query.matchesQuery('shopGoodsObj', shopGoods);
    }
    query.notEqualTo('status',-1)
    query.doesNotExist('groupStartTime')
    query.equalTo("groupStartTime",null)
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shopGoodsObj')
    query.exists('shopGoodsObj')
    query.descending("createdAt");
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            var obj = {};
            var data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get('objectId');
                temObj["title"] = item.get('shopGoodsObj')?item.get('shopGoodsObj').get("title"):"";
                temObj["price"] = item.get('shopGoodsObj')?item.get('shopGoodsObj').get("price"):"";
                temObj["shopIcon"] = item.get('shopGoodsObj').get("picName") ? qn + item.get('shopGoodsObj').get("picName") : '';
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.addShopPopUpLogo = addShopPopUpLogo;

function addShopPopUpLogo(params, callback) {
    let logo = params.logo
    let goodsShopType = Number(params.shopGoodsType)
    let goodsUrl = params.goodsUrl

    let ShopPopupLogo = AV.Object.extend('Shop_popup_logo');
    let shopPopupLogo = new ShopPopupLogo();
    shopPopupLogo.set('goodsShopType', goodsShopType);
    shopPopupLogo.set('logo', logo);
    shopPopupLogo.set('goodsUrl', goodsUrl);
    let shop_goods_OId = params.shopGoodsOId
    if (shop_goods_OId) {
        let shop_goods_Obj = AV.Object.createWithoutData('Shop_goods', shop_goods_OId);
        shopPopupLogo.set('shop_goods_OId', shop_goods_OId);
        shopPopupLogo.set('shop_goods_Obj', shop_goods_Obj);
    }
    let score_shop_goods_OId = params.scoreShopGoodsOId
    if (score_shop_goods_OId) {
        let score_shop_goods_Obj = AV.Object.createWithoutData('Score_shop_goods', score_shop_goods_OId);
        shopPopupLogo.set('score_shop_goods_OId', score_shop_goods_OId);
        shopPopupLogo.set('score_shop_goods_Obj', score_shop_goods_Obj);
    }
    shopPopupLogo.save().then(result => {
        if (result) {
            callback(result)
        } else {
            console.log('添加商城弹出LOGO失败')
        }
    }).catch(errs => {
        console.log(errs)
    })
}

exports.getShopPopUpLogo = getShopPopUpLogo;

function getShopPopUpLogo(page, num, goodsInShopType) {

    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    let query = new AV.Query('Shop_popup_logo');

    if (goodsInShopType != '' || goodsInShopType != undefined || goodsInShopType != null) {
        let goodsShopType = Number(goodsInShopType)
        if (goodsShopType > -1) {
            query.equalTo('goodsShopType', goodsShopType)
        }
    }
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shop_goods_Obj');
    query.include('score_shop_goods_Obj');
    query.include('score_shop_goods_Obj.shopGoodsObj');
    query.descending('createdAt');
    return query.find().then(function (result) {
        return query.count().then(function (count) {
            let obj = {};
            let data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let temObj = {};
                temObj["objectId"] = item.get("objectId");
                temObj["logo"] = item.get("logo");
                temObj["goodsUrl"] = item.get("goodsUrl");
                temObj["goodsShopType"] = item.get("goodsShopType");
                if (item.get("goodsShopType") == 0) {
                    let shopGoodsObj = item.get("shop_goods_Obj");
                    temObj["goodsShopOId"] = shopGoodsObj ? shopGoodsObj.get('objectId') : '';
                    temObj["title"] = shopGoodsObj ? shopGoodsObj.get('title') : '';
                    temObj["shopIcon"] = shopGoodsObj ? qn + shopGoodsObj.get('picName') : '';
                } else if (item.get("goodsShopType") == 1) {
                    let scoreShopGoodsObj = item.get("score_shop_goods_Obj").get('shopGoodsObj')
                    temObj["goodsShopOId"] = item.get("score_shop_goods_Obj") ? item.get("score_shop_goods_Obj").get('objectId') : '';
                    temObj["title"] = scoreShopGoodsObj ? scoreShopGoodsObj.get('title') : '';
                    temObj["shopIcon"] = scoreShopGoodsObj ? qn + scoreShopGoodsObj.get('picName') : '';
                } else {
                    console.log('未知商品所属商城类型!')
                    return '未知商品所属商城类型！'
                }

                temObj["updatedAt"] = moment(item.get('updatedAt')).format('YYYY-MM-DD HH:mm:ss');
                temObj["createdAt"] = moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

exports.delShopPopUpLogo = delShopPopUpLogo;

async function delShopPopUpLogo(objectId) {
    if (objectId) {
        var question = AV.Object.createWithoutData('Shop_popup_logo', objectId);
        return question.destroy().then(result => {
            if (result) {
                return result.id
            }
        }).catch(error => {
            console.log(error)
        })
    } else {
        console.log('未获取到商城弹出LOGO的ID！')
    }
}



exports.getParentGoodsType = getParentGoodsType;
function getParentGoodsType(callback) {
    var query = new AV.Query('Shop_good_type');
    query.doesNotExist('parentId')
    query.equalTo("fatherCode", '1');
    query.ascending("sortNum");
    query.find().then(function (result) {
        var resultArr = [];
        var fatherObj = {name: "商品分类", id: "xz", expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["name"] = result[i].get("name");
            temObj["objectId"] = result[i].get("objectId");
            temObj["pid"] = "xz";
            resultArr.push(temObj);
        }
        callback(resultArr)
    }, function (error) {
        console.log(error);
        callback(error);
    })
}

exports.parentGoodsTypeTreeWithoutParent = parentGoodsTypeTreeWithoutParent;
function parentGoodsTypeTreeWithoutParent(callback) {
    var query = new AV.Query('Shop_good_type');
    query.doesNotExist('parentId')
    // query.equalTo("fatherCode", '1');
    query.ascending("sortNum");
    query.find().then(function (result) {
        var resultArr = [];
        var fatherObj = {name: "商品分类", id: "xz", expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["id"] = result[i].get("code");
            temObj["name"] = result[i].get("name");
            temObj["objectId"] = result[i].get("objectId");
            temObj["pid"] = "xz";
            resultArr.push(temObj);
        }
        callback(resultArr)
    }, function (error) {
        console.log(error);
        callback(error);
    })
}


exports.fetchGoodsTypeBanners = fetchGoodsTypeBanners;
function fetchGoodsTypeBanners(params,callback) {

    let {type} = params
    var query = new AV.Query('goods_banner');
    query.doesNotExist('parentId');
    query.include('shopGoodsTypeObj');
    query.ascending("sortNum");
    query.equalTo("shopGoodsTypeOId",type)
    query.find().then(function (res) {
        var resultArr = [];
        for (let item of res){
            let obj = {
                objectId:item.id,
                picURL:item.get('picUrl')?(remoteImageUrlDomain+item.get('picUrl')):"",
                sort:item.get('sort'),
                goodsTypeName:item.get('shopGoodsTypeObj').get('name'),
                name:item.get("name")
            }
            resultArr.push(obj)
        }


        callback(resultArr)
    }, function (error) {
        console.log(error);
        callback(error);
    })
}


exports.fetchBannerRelationGoods = fetchBannerRelationGoods;
function fetchBannerRelationGoods(params,callback) {

  let {goodsBannerOId} = params
  var query = new AV.Query('banner_relation_goods');
  query.include('scoreGoodsObj');
  query.include('scoreGoodsObj.shopGoodsObj');
  query.include('scoreGoodsObj.externalGoodsObj');
  query.include("goodsObj");
  query.ascending("sort");
  query.equalTo("goodsBannerOId",goodsBannerOId)
  query.find().then(function (res) {
    var resultArr = [];
    for (let item of res){
        var goodsId = ''
        var goodsName = ''
        if (item.get("classify")==0){
          goodsId = item.get("scoreGoodsOId")
          if (item.get('scoreGoodsObj').get('shopGoodsObj')){
              goodsName = item.get('scoreGoodsObj').get('shopGoodsObj').get('title')
            } else if (item.get('scoreGoodsObj').get('externalGoodsObj')){
                goodsName = item.get('scoreGoodsObj').get('externalGoodsObj').get('sourceGoodsName')
            }

        } else if (item.get("classify")==1){
          goodsId = item.get("goodsOId")
          goodsName = item.get('goodsObj').get('title')
        }
      let obj = {
        objectId:item.id,
        goodsId:goodsId,
        goodsName:goodsName,
        sort:item.get('sort')
      }
      resultArr.push(obj)
    }

    callback(resultArr)
  }, function (error) {
    console.log(error);
    callback(error);
  })
}

exports.addBannerGoodsRelation = addBannerGoodsRelation;
function addBannerGoodsRelation(params,callback) {


  let {typeName,goodsId,shopGoodTypeId} = params
  console.log(typeName,goodsId,shopGoodTypeId)

  let banner_relation_good = AV.Object.extend('banner_relation_goods')
  let bannerRelationGoods = new banner_relation_good()

  bannerRelationGoods.set('goodsBannerOId',shopGoodTypeId)
  bannerRelationGoods.set('goodsBannerObj',AV.Object.createWithoutData('goods_banner',shopGoodTypeId))
  if (typeName == "0"){//积分商品
    bannerRelationGoods.set("classify",0)

    bannerRelationGoods.set("scoreGoodsOId",goodsId)

    bannerRelationGoods.set("scoreGoodsObj",AV.Object.createWithoutData('Score_shop_goods',goodsId))

  }else{//普通商品
    bannerRelationGoods.set("classify",1)
    bannerRelationGoods.set("goodsOId",goodsId)

    bannerRelationGoods.set("goodsObj",AV.Object.createWithoutData('Shop_goods',goodsId))
  }
  bannerRelationGoods.save().then(res=>{
    callback(10000)
  }).catch(error=>{
    console.log(error)
    callback(10001)
  })

}



exports.removeBannerRelationGoods = removeBannerRelationGoods;
function removeBannerRelationGoods(params,callback) {


    let {objectId} = params


    AV.Object.createWithoutData('banner_relation_goods',objectId).destroy().then(res=>{
        callback(10000)
    }).catch(error=>{
        callback(10001)
    });

}

exports.removeGoodsBanner = removeGoodsBanner;
function removeGoodsBanner(params,callback) {


    let {objectId} = params

    AV.Object.createWithoutData('goods_banner',objectId).destroy().then(res=>{
        callback(10000)
    }).catch(error=>{
        callback(10001)
    });

}
exports.fetchGoodsBannerById = fetchGoodsBannerById;
function fetchGoodsBannerById(objectId,callback) {



    let query = new AV.Query('goods_banner')
    query.equalTo('objectId',objectId)
    query.first().then(res=>{
        if (res){
            let obj = {
                objectId:res.id,
                name:res.get('name'),
                shopGoodTypeId:res.get('shopGoodsTypeOId'),
                sort:res.get('sort')
            }
            callback(obj)
        }else{
            callback(10001)
        }

    })

    // AV.Object.createWithoutData('goods_banner',objectId).destroy().then(res=>{
    //     callback(10000)
    // }).catch(error=>{
    //     callback(10001)
    // });

}



exports.getGoodsType = getGoodsType;
function getGoodsType(data,callback) {
    // console.log(data)
    let parentId = data.parentId
    let page = data.page
    let num = data.num

    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    var query = new AV.Query('Shop_good_type');
    query.limit(num);
    query.skip((page - 1) * num);
    query.ascending("sortNum");
    query.equalTo("fatherCode", '1');


    if (parentId == '' || parentId == undefined || parentId == null) {
        query.doesNotExist('parentId')
    } else  {
        query.exists('parentId')
        query.equalTo("parentId", parentId);
    }
    query.find().then(function (result) {
        query.count().then(function (count) {
            let obj = {};
            var data = [];
            for (var i = 0; i < result.length; i++) {
                var temObj = {};
                temObj["objectId"] = result[i].get("objectId");
                temObj["parentId"] = result[i].get("parentId");
                temObj["name"] = result[i].get("name");
                temObj["sortNum"] = result[i].get("sortNum");
                temObj["updatedAt"] = moment(result[i].updatedAt).format('YYYY年MM月DD HH:mm:ss');
                temObj["createdAt"] = moment(result[i].createdAt).format('YYYY年MM月DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            callback(obj);
        }).catch(err=>{
            console.log(err);
        })

    }, function (error) {
        console.log(error);
        // callback(error);
    })
}

exports.getGoodTypeForOId = getGoodTypeForOId
function getGoodTypeForOId(objectId,callback){
    var query = new AV.Query('Shop_good_type');
    query.equalTo('objectId',objectId)
    query.first().then(result=>{
        var temObj = {}
        temObj.objectId = result.id
        temObj.name = result.get('name')
        temObj.sortNum = result.get('sortNum')
        callback(temObj)
    }).catch(error=>{
        console.log(error);
    })
}

exports.addGoodsType = addGoodsType;
function addGoodsType(data,callback) {
    // console.log(data)
    let name = data.name
    let iconId = data.iconId
    let parentId = data.parentId
    let sortNum = Number(data.sortNum)
    let ShopGoodType = AV.Object.extend('Shop_good_type');
    let shopGoodType = new ShopGoodType();
    if (iconId != null && iconId != undefined && iconId != "") {

        shopGoodType.set("icon", AV.File.createWithoutData(iconId));
    }
    if (parentId != null && parentId != undefined && parentId != "") {
        shopGoodType.set('parentId', parentId);
    }
    shopGoodType.set('name', name);
    // shopGoodType.set('sortNum', 0);
    shopGoodType.set('type', '1');
    shopGoodType.set('level', 1);
    shopGoodType.set('status', '1');
    shopGoodType.set('fatherCode', '1');
    shopGoodType.set('code', '0');

    shopGoodType.save().then(goodsType=>{
        callback(goodsType)
    }).catch(error=>{
        console.log(error,"--------")
    })
}
exports.editGoodsType = editGoodsType;
function editGoodsType(data,callback) {
    let objectId = data.objectId
    let name = data.name
    let sortNum = Number(data.sortNum)
    // console.log(data)
    let shopGoodsTypeObj = AV.Object.createWithoutData('Shop_good_type', objectId);
    shopGoodsTypeObj.set('name', name);
    shopGoodsTypeObj.set('sortNum', sortNum);
    return shopGoodsTypeObj.save().then(function (result) {
        callback(result);
    }, function (error) {
        console.log(error);
    })
}

exports.delGoodsType = delGoodsType;
async function delGoodsType(objectId) {
    // console.log(objectId)
    if (objectId) {
        // let changeScoreShopGoodsTypeId = new Promise((resolve,reject) =>{
        let scoreShopQueryForOId = new AV.Query('Score_shop_goods');
        scoreShopQueryForOId.equalTo('shopGoodsTypeOId',objectId)
        let scoreShopQueryForPId = new AV.Query('Score_shop_goods');
        scoreShopQueryForPId.equalTo('shopGoodsTypeParentOId',objectId)
        let query = AV.Query.or(scoreShopQueryForOId, scoreShopQueryForPId);
        let changeScoreShopGoodsTypeId = query.find().then(scoreShopGoodsObjs=>{
            // console.log('scoreShopGoodsObjs',scoreShopGoodsObjs)
            var scoreShopGoodsObjsArr = []
            var otherOId = '5b6e4082a22b9d003175ebda'
            var otherObj = AV.Object.createWithoutData('Shop_good_type', otherOId);
            var otherPId = '5b6e406d17d0090035be2362'
            var otherObj = AV.Object.createWithoutData('Shop_good_type', otherPId);
            scoreShopGoodsObjs.map(scoreShopGoodsItem=>{
                // console.log('scoreShopGoodsItem',scoreShopGoodsItem)
                // scoreShopGoodsItem.set('shopGoodsTypeOId',otherOId)
                // scoreShopGoodsItem.set('shopGoodsTypeObj',otherObj)
                scoreShopGoodsItem.set('shopGoodsTypeParentOId',otherPId)
                scoreShopGoodsItem.set('shopGoodsTypeParentObj',otherObj)
                scoreShopGoodsObjsArr.push(scoreShopGoodsItem)
            })
            return   AV.Object.saveAll(scoreShopGoodsObjsArr).then(scoreShopGoodsItemSaveResult=>{
                // console.log('scoreShopGoodsItemSaveResult',scoreShopGoodsItemSaveResult)
                // resolve(scoreShopGoodsItemSaveResult)
                return scoreShopGoodsItemSaveResult
            }).catch(scoreShopGoodsItemSaveError=>{
                return scoreShopGoodsItemSaveError
                // reject(scoreShopGoodsItemSaveError)
            })
        }).catch(errorOId=>{
            console.log(errorOId)
            // reject(errorOId)
            return errorOId
        })
        // })
        // let destroyAllChildGoodsType = new Promise((resolve,reject) =>{
        var query1 = new AV.Query('Shop_good_type');
        query1.equalTo('parentId',objectId)
        let destroyAllChildGoodsType =    query1.find().then(childs=>{
            return  AV.Object.destroyAll(childs).then(destroyChildsResult=>{
                // console.log(destroyChildsResult)
                return destroyChildsResult
                // resolve(destroyChildsResult)
            }).catch(destroyChildsErr=>{
                console.log(destroyChildsErr)
                return destroyChildsResult

                // reject(destroyChildsErr)
            })
        }).catch(err=>{
            console.log(err)

            return false
            // })
        })
        return Promise.all([changeScoreShopGoodsTypeId,destroyAllChildGoodsType]).then((promiseAllResult)=>{
            // console.log('promiseAllResult',promiseAllResult)
            var shopGoodsTypeObj = AV.Object.createWithoutData('Shop_good_type', objectId);
            return shopGoodsTypeObj.destroy().then(result => {
                if (result) {
                    return result.id
                }
            }).catch(error => {
                console.log(error)
            })
        }).catch((promiseAllerr)=>{
            console.log(promiseAllerr)
        })
    } else {
        console.log('未获取到商品分类的ID！')
    }
}
exports.selectGoodsTypeForShopIntergation = selectGoodsTypeForShopIntergation;
function selectGoodsTypeForShopIntergation(callback) {
    var query = new AV.Query('Shop_good_type');
    query.equalTo("fatherCode",'1');
    // query.doesNotExist('parentId')
    query.ascending("sortNum");
// query.addAscending('fatherCode');
    query.find().then(function (goodsType) {
        var data = []
        goodsType.map(item=>{
            let tempDic = {}
            let parentId = item.get('parentId') ? item.get('parentId'):''
            tempDic.id = item.id
            tempDic.text = item.get('name')
            if (parentId != ''){
                tempDic.pid = item.get('parentId')
            }
            data.push(tempDic)
        })
        callback(data)
    }, function (error) {
        console.log(error)
    })
}
exports.getBusinessCollegeClassify = getBusinessCollegeClassify;

function getBusinessCollegeClassify() {
    let query = new AV.Query('Dictionary');
    query.equalTo('type', '15')
    query.ascending("sortNum")
    return query.find().then(result => {
        var resultArr = [];

        var fatherObj = {name: "商学院分类", objectId: "xz", expanded: true};
        resultArr.push(fatherObj);
        for (var i = 0; i < result.length; i++) {
            var temObj = {};
            temObj["objectId"] = result[i].get("objectId");
            temObj["name"] = result[i].get("name");
            temObj["pid"] = "xz";
            resultArr.push(temObj);
        }
        return resultArr
    }).catch(error => {
        console.log(error)
        return null
    })
}

exports.getBusinessCollegeSubList = getBusinessCollegeSubList;
function getBusinessCollegeSubList(dictionaryOId, pageIndex, pageSize) {

    if (!pageIndex||pageIndex == '') {
        pageIndex = 0;
    } else {
        pageIndex = parseInt(pageIndex);
    }
    if (!pageSize||pageSize == '') {
        pageSize = 20;
    } else {
        pageSize = parseInt(pageSize);
    }

    var query = new AV.Query('Business_college');

    query.skip(pageIndex * pageSize);
    query.limit(pageSize);
    query.equalTo("dictionaryOId",dictionaryOId)
    query.notEqualTo("status",-1)
    query.descending('updatedAt');

    return query.find().then(function (result) {
            return   query.count().then(function (count) {
                var obj = {};
                var data = [];
                var num = 0;
                for (var i = 0; i < result.length; i++) {
                    var temObj = {};
                    num++;
                    temObj["objectId"] = result[i].get("objectId");
                    temObj["title"] = result[i].get("title");
                    temObj["content"] = result[i].get("content");
                    temObj["createdAt"] = moment(result[i].get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                    temObj["updatedAt"] = moment(result[i].get("updatedAt")).format('YYYY-MM-DD HH:mm:ss');
                    data.push(temObj);
                }
                obj.data = data;
                obj.total = count;
                return obj;
            })
        }, function (error) {
            console.log(error)
            return null;
        }
    )

}

exports.deleteBusinessCollegeSubItem = deleteBusinessCollegeSubItem;
function deleteBusinessCollegeSubItem(objectId) {
    var query = new AV.Query('Business_college');
    query.equalTo("objectId",objectId)
    query.notEqualTo("status",-1)
    return query.first().then(result=>{
        if(!result){
            return null
        }
        result.set("status",-1)
        return result.save().then(result=>{
            return result
        }).catch(error=>{
            console.log(error)
            return null
        })
    }).catch(error=>{
        console.log(error)
        return null
    })
}
exports.addBusinessCollegeSubItem = addBusinessCollegeSubItem;
async function addBusinessCollegeSubItem(body) {
    let classifyOId = body.classifyOId;
    let title = body.title;
    let content = body.content;
    if(!classifyOId||classifyOId==""){
        return null
    }
    if(!title||title==""){
        return null
    }
    if(!content||content==""){
        return null
    }

    let  coverUrl=await getCoverUrl(content);
    let type=0;
    let url="";
    if(coverUrl){
        url=coverUrl;
        type=1;
    }
    let BusinessCollage = AV.Object.extend('Business_college');
    let businessCollage = new BusinessCollage();
    businessCollage.set("title", title);
    businessCollage.set("content", content);
    businessCollage.set("url", url);
    businessCollage.set("dictionaryOId", classifyOId);
    businessCollage.set("dictionaryObj", AV.Object.createWithoutData("Dictionary", classifyOId));
    businessCollage.set("type", type);
    return businessCollage.save().then(result=>{
        return result;
    }).catch(error=>{
        console.log(error)
        return null;
    })

}
exports.editBusinessCollegeSubItem = editBusinessCollegeSubItem;
async function editBusinessCollegeSubItem(body) {
    let objectId = body.objectId;
    let title = body.title;
    let content = body.content;
    if(!objectId||objectId==""){
        return null
    }
    if(!title||title==""){
        return null
    }
    if(!content||content==""){
        return null
    }
    let  coverUrl=await getCoverUrl(content);
    let type=0;
    let url="";
    if(coverUrl){
        url=coverUrl;
        type=1;
    }
    let query = new AV.Query('Business_college');
    return query.get(objectId).then(result=>{
        result.set("title", title);
        result.set("content", content);
        result.set("url", url);
        result.set("type", type);
        result.save().then(result=>{
            return result;
        }).catch(error=>{
            console.log(error)
            return null;
        })
    }).catch(error=>{
        console.log(error)
        return null;
    })

}

function getCoverUrl(content){
    let m,
        urls = [],
        rex = /<img.*?src="([^">]*\/([^">]*?))".*?>/g;

    while (m = rex.exec(content) ) {
        urls.push( m[1] );
    }
    if(urls&&urls.length>0){
        return  urls[0]
    }else{
        return false
    }
}

function getVideoUrl(content){
    let m,
        urls = [],
        rex = /<video.*?src="([^">]*\/([^">]*?))".*?>/g;

    while (m = rex.exec(content) ) {
        urls.push( m[1] );
    }
    if(urls&&urls.length>0){
        return  urls[0]
    }else{
        return false
    }
}

/**
 * 保存访问记录
 * @type {saveRequestRecord}
 */
exports.saveRequestLog=saveRequestLog
function saveRequestLog(req){
    let userOId=""
    if(req.currentUser){
        userOId = req.currentUser.id;
    }
    let url=req.url.split("?")[0]
    let index=url.indexOf("/v1")
    if(index!=0){
        return;
    }
    let method=req.method
    let params=""
    if(method=="GET"){
        params=JSON.stringify(req.query)
    }else{
        params=JSON.stringify(req.body)
    }
    let RequestLog = AV.Object.extend('RequestLog');
    let requestLog = new RequestLog();
    requestLog.set("url", url);
    requestLog.set("params", params);
    if(userOId&&userOId!=""){
        requestLog.set("userOId", userOId);
        requestLog.set("userObj", AV.Object.createWithoutData("_User", userOId));
    }
    requestLog.save().catch(error=>{
    })
}

/**
 * 批量发货
 * @param args
 */
exports.batchCourierDeliveryXLSX = function (...args) {
    let [filePath, uId, callback] = args
    let fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
    let stream = fs.createWriteStream(`${fileName}`)
    request(filePath).pipe(stream).on('close', async () => {
        const buffer = fs.readFileSync(`${fileName}`)
        const result = JSON.parse(JSON.stringify(xlsx.parse(buffer)));
        let orderList=[];
        const list = result[0].data.slice(1)
        let tempData=null;
        let orderMap=null;
        for ( var i = 0; i < list.length; i++) {
            tempData=null;
            tempData=list[i];
            if(tempData.length==2||tempData.length==3){
                if(tempData[0]!=""&&tempData[0]!=null){
                    tempData[0]=tempData[0].toString();
                    if(tempData[0].replace(/\s/g, "")===parseInt(tempData[0].replace(/\s/g, "")).toString()){
                        orderMap={};
                        orderMap["orderCode"]=parseInt(tempData[0].replace(/\s/g, ""));
                        orderMap["logisticsCom"]=tempData[1].replace(/\s/g, "");
                        orderMap["logisticsComCode"]=apis["logisticsComCode"][orderMap["logisticsCom"]];
                        if(tempData.length==3){
                            orderMap["expressCode"]=(tempData[2]+'').replace(/\s/g, "");
                        }else{
                            orderMap["expressCode"]="";
                        }
                        orderList.push(orderMap);
                    }
                }
            }
        }
        if(orderList.length>0){
            if(orderList.length>1000){
                callback("最多只能对1000条数据进行发货",null);
            }else {
                var orderCodeArry = [];

                for (var i = 0; i < orderList.length; i++) {
                    orderMap[orderList[i]["orderCode"]] = orderList[i];
                    orderCodeArry.push(orderList[i]["orderCode"]);
                }
                //查询订单
                var orderStatus = [apis["order"]["status_noSend"], apis["order"]["status_noReceive"]]
                var orderQuery = new AV.Query('Shop_order');
                orderQuery.equalTo("sellerOId", uId);
                orderQuery.containedIn("orderCode", orderCodeArry);
                orderQuery.containedIn("status", orderStatus);
                orderQuery.include("buyerObj");
                orderQuery.limit(1000);
                orderQuery.find().then(orderObjs => {
                    if (orderObjs.length == 0) {
                        callback("很抱歉，根据您上传的文件未查询到有效数据", null);
                    } else {
                        //执行批量发货
                        var saveOrderArray = [];
                        for (var i = 0; i < orderObjs.length; i++) {
                            if (orderObjs[i].get("orderSendCount") == "" || orderObjs[i].get("orderSendCount") == null || orderObjs[i].get("orderSendCount") < 2) {
                                //如果发货方式没发生变化则跳过
                                if (orderObjs[i].get("logisticsComCode") == "-1" && orderMap[orderObjs[i].get("orderCode")]["logisticsComCode"] == "-1") {
                                    continue;
                                }
                                //如果发货方式没发生变化则跳过
                                if (orderObjs[i].get("logisticsComCode") == orderMap[orderObjs[i].get("orderCode")]["logisticsComCode"] && orderMap[orderObjs[i].get("orderCode")]["expressCode"] == orderObjs[i].get("expressCode")) {
                                    continue;
                                }
                                orderObjs[i].set("logisticsCom", orderMap[orderObjs[i].get("orderCode")]["logisticsCom"]);//快递公司
                                orderObjs[i].set("expressCode", orderMap[orderObjs[i].get("orderCode")]["expressCode"]);//快递号
                                orderObjs[i].set("logisticsComCode", orderMap[orderObjs[i].get("orderCode")]["logisticsComCode"]);//物流编号
                                orderObjs[i].set("deliverTime", new Date());
                                if (orderObjs[i].get("orderSendCount") == "" || orderObjs[i].get("orderSendCount") == null || orderObjs[i].get("orderSendCount") == undefined) {
                                    orderObjs[i].set("orderSendCount", 1);
                                } else {
                                    orderObjs[i].increment("orderSendCount", 1);
                                }
                                orderObjs[i].set("oldStatus", orderObjs[i].get("status"));
                                orderObjs[i].set("status", apis['order']['status_noReceive']);
                                orderObjs[i].set("task", apis["taskType"]["orderReceive"]);//定时任务
                                orderObjs[i].set("taskTime", new Date(moment().add(apis["taskType"]["orderReceiveDate"], 'days')));//定时任务时间
                                saveOrderArray.push(orderObjs[i]);
                            }
                        }
                        AV.Object.saveAll(saveOrderArray, function(list, error) {

                            fs.unlink(`${fileName}`, () => {
                                if (error) {
                                    callback(error,null);
                                }else{
                                    sendOrderTip(list, function (error, result) {
                                    });
                                    callback(null,list);
                                }
                            })

                        })
                    }
                }).catch(error => {
                    console.log("Shop_order-->" + error)
                    callback(error, null);
                })
            }
        }else{
            callback("并没在上传的文件中检索到订单数据，请检查",null);
        }
    })
}

exports.getShop=async function(userOId){
    let shop1=await getShopFromShop_shop(userOId);
    if(shop1){
        return shop1
    }else{
        let shop2=await getShopFromUserRole(userOId)
        if(shop2){
            return shop2
        }else{
            return false
        }
    }
}

function getShopFromShop_shop(userOId){
    let query=new AV.Query("Shop_shop")
    query.equalTo("userOId",userOId)
    return query.first().then(result=>{
        if(!result) {
            return false
        }
        return result;
    }).catch(error=>{
        console.log(error)
        return false
    })

}

function getShopFromUserRole(userOId){
    let query=new AV.Query("UserRole")
    query.equalTo("userOId",userOId)
    query.include("shopObj")
    return query.first().then(result=>{
        if(!result){
            return false
        }
        return result.get("shopObj")
    }).catch(error=>{
        console.log(error)
        return false
    })

}

exports.groupGoodsSearch = groupGoodsSearch;

function groupGoodsSearch(page, num, goodsName,goodsParentTypeID) {
    if (page == '' || page == undefined || page == null) {
        page = 1;
    } else {
        page = parseInt(page);
    }
    if (num == '' || num == undefined || num == null) {
        num = 20;
    } else {
        num = parseInt(num);
    }
    let query = new AV.Query('Score_shop_goods');
    if (goodsName == '' || goodsName == undefined || goodsName == null) {
    } else {
        let shopGoods = new AV.Query('Shop_goods');
        shopGoods.contains('title', goodsName);
        query.matchesQuery('shopGoodsObj', shopGoods);
    }
    if (goodsParentTypeID == '' || goodsParentTypeID == undefined || goodsParentTypeID == null) {
    } else {
        query.equalTo('shopGoodsTypeParentOId',goodsParentTypeID)
    }

    query.notEqualTo("status", -1);
    query.limit(num);
    query.skip((page - 1) * num);
    query.include('shopGoodsObj');
    query.include('shopGoodsObj.shopObj');
    query.include('shopGoodsTypeParentObj');
    query.include('shopGoodsTypeObj');
    query.descending('groupEndTime');
    query.notEqualTo("groupStartTime",null)
    return query.find().then(function (result) {
        return query.count().then(async function (count) {
            let obj = {};
            let data = [];
            var qn = 'http://tribemedia.aladada.com/';
            for (let item of result) {
                let shopGoodsVal = item.get("shopGoodsObj");
                let temObj = {};
                temObj.id = item.get("objectId");
                temObj.objectId = shopGoodsVal ? shopGoodsVal.get('objectId') : '';
                temObj.title = shopGoodsVal ? shopGoodsVal.get('title') : '';
                temObj.goodsName = shopGoodsVal.get("title")

                let parentGoodsTypeName = item.get('shopGoodsTypeParentObj') ? item.get('shopGoodsTypeParentObj').get('name') : '';
                let goodsTypeName = item.get('shopGoodsTypeObj') ? item.get('shopGoodsTypeObj').get('name') : '';
                if (parentGoodsTypeName != '' && goodsTypeName != ''){
                    temObj.goodsType = parentGoodsTypeName + '-' + goodsTypeName;
                } else {
                    temObj.goodsType = parentGoodsTypeName;
                }

                temObj.shopGoodsTypeParentOId = item.get('shopGoodsTypeParentOId');
                temObj.sortNum = item.get('sortNum');

                temObj.groupPrice = item.get('groupPrice');
                temObj.groupScore = item.get('groupScore');
                temObj.limitNum= item.get('limitNum');
                temObj.groupPeopleNum = item.get('groupPeopleNum');
                temObj.minGroupPeopleNum = item.get('minGroupPeopleNum');
                temObj.groupDuration = item.get('groupDuration');
                temObj.groupStartTime = moment(item.get('groupStartTime')).format('YYYY-MM-DD HH:mm:ss');
                temObj.groupEndTime = moment(item.get('groupEndTime')).format('YYYY-MM-DD HH:mm:ss');
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}
exports.addGroupActivity= function addGroupActivity(req){
    let scoreShopGoodsOId=req.body.scoreShopGoodsOId;
    let groupPrice=Number(req.body.groupPrice);
    let groupScore=Number(req.body.groupScore);
    let groupPeopleNum=Number(req.body.groupPeopleNum);
    let limitNum=Number(req.body.limitNum);
    let minGroupPeopleNum=Number(req.body.minGroupPeopleNum);
    let groupDuration=Number(req.body.groupDuration);
    let groupStartTime= new Date(req.body.groupStartTime);
    let groupEndTime=new Date(req.body.groupEndTime);

    let query=new AV.Query("Score_shop_goods")
    query.equalTo("groupStartTime",null)
    return query.get(scoreShopGoodsOId).then(result=>{
        if(!result){
            return -1
        }
        result.set("groupPrice",groupPrice)
        result.set("groupScore",groupScore)
        result.set("groupPeopleNum",groupPeopleNum)
        result.set("limitNum",limitNum)
        result.set("minGroupPeopleNum",minGroupPeopleNum)
        result.set("groupDuration",groupDuration)
        result.set("groupStartTime",groupStartTime)
        result.set("groupEndTime",groupEndTime)
        return result.save().then(result=>{
            return 1
        }).catch(error=>{
            console.log(error)
            return -1
        })
    }).catch(error=>{
        console.log(error)
        return -1
    })

}

exports.deleteGroup= function deleteGroup(req,callback){
    let ids = req.body.ids;
    if(!ids||ids==""||ids.length<=0){
        callback("10002", null)
    }
    console.log("deleteGroup-->"+ids)
    let query=new AV.Query("Score_shop_goods")
    query.exists("groupStartTime")
    query.containedIn("objectId",ids)
    query.find().then(result=>{
        let array=[]
        for (let item of result) {
            item.set("groupPrice",0)
            item.set("groupScore",0)
            item.set("groupPeopleNum",0)
            item.set("limitNum",0)
            item.set("minGroupPeopleNum",0)
            item.set("groupStartTime",null)
            item.set("groupEndTime",null)
            array.push(item);
        }
        AV.Object.saveAll(array).then(resolve => {
            console.log("10001")
            callback(null, "10001")
        }, reject => {
            console.log("10002")
            callback("10002", null)
        })
    }).catch(error=>{
        console.log(error)
        callback("10002", null)
    })
}


exports.editGroupActivity= function editGroupActivity(req){
    let objectId=req.body.objectId;
    let groupPrice=Number(req.body.groupPrice);
    let groupScore=Number(req.body.groupScore);
    let groupPeopleNum=Number(req.body.groupPeopleNum);
    let limitNum=Number(req.body.limitNum);
    let minGroupPeopleNum=Number(req.body.minGroupPeopleNum);
    let groupDuration=Number(req.body.groupDuration);
    let groupStartTime= new Date(req.body.groupStartTime);
    let groupEndTime=new Date(req.body.groupEndTime);

    let query=new AV.Query("Score_shop_goods")
    query.notEqualTo("groupStartTime",null)
    return query.get(objectId).then(result=>{
        if(!result){
            console.log("editGroupActivity-->"+objectId)
            return -1
        }
        result.set("groupPrice",groupPrice)
        result.set("groupScore",groupScore)
        result.set("groupPeopleNum",groupPeopleNum)
        result.set("limitNum",limitNum)
        result.set("minGroupPeopleNum",minGroupPeopleNum)
        result.set("groupDuration",groupDuration)
        result.set("groupStartTime",groupStartTime)
        result.set("groupEndTime",groupEndTime)
        return result.save().then(result=>{
            return 1
        }).catch(error=>{
            console.log(error)
            return -1
        })
    }).catch(error=>{
        console.log(error)
        return -1
    })

}

exports.groupSearch = groupSearch;
function groupSearch(req) {
    let pageIndex = req.body.pageIndex;
    let pageSize =  req.body.pageSize;
    let groupId = req.body.groupId;
    let groupLaunchTimeFrom = req.body.groupLaunchTimeFrom;
    let groupLaunchTimeTo = req.body.groupLaunchTimeTo;
    let groupStatus = req.body.groupStatus;

    if (pageIndex == '' || !pageIndex ) {
        pageIndex = 1;
    } else {
        pageIndex = parseInt(pageIndex);
    }
    if (pageSize == '' || !pageSize) {
        pageSize = 20;
    } else {
        pageSize = parseInt(pageSize);
    }
    var query=new AV.Query('Fight_groups');
    if(groupLaunchTimeFrom!=""&&groupLaunchTimeFrom&&groupLaunchTimeTo!=""&&groupLaunchTimeTo){
        var startDateQuery = new AV.Query('Fight_groups');
        startDateQuery.greaterThanOrEqualTo('createdAt', new Date(groupLaunchTimeFrom));

        var endDateQuery = new AV.Query('Fight_groups');
        endDateQuery.lessThan('createdAt', new Date(groupLaunchTimeTo));

        query = AV.Query.and(startDateQuery, endDateQuery);
    }

    if(groupId!=""&&groupId){
        query.equalTo("objectId", groupId);
    }
    console.log("groupStatus-pageIndex->"+pageIndex)
    console.log("groupStatus-222->"+groupStatus)
    if(groupStatus!=""&&groupStatus&&groupStatus!=100){
        query.equalTo("status", Number(groupStatus));
    }
    query.include('scoreShopGoodsObj.shopGoodsObj');
    query.limit(pageSize);
    query.skip((pageIndex- 1) * pageSize);

    query.descending('createdAt');

    return query.find().then(function (result) {
        return query.count().then(async function (count) {
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj.objectId=item.id
                let scoreShopGoodsObj=item.get("scoreShopGoodsObj")
                if(scoreShopGoodsObj){
                    let shopGoodsObj = scoreShopGoodsObj.get('shopGoodsObj')
                    temObj.goodsOId = shopGoodsObj ? shopGoodsObj.get('objectId') : '';
                    temObj.goodsName = shopGoodsObj ? shopGoodsObj.get('title') : '';
                    temObj.groupPeopleNum=scoreShopGoodsObj.get("groupPeopleNum")
                    temObj.duration=scoreShopGoodsObj.get("groupDuration")
                }

                temObj.createdAt=moment(item.get('createdAt')).format('YYYY-MM-DD HH:mm:ss');
                temObj.participantsNum=await getParticipantsNum(temObj.objectId)

                temObj.status=item.get("status")
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        })
    })
}

function getParticipantsNum(fightGroupOId) {
    var shopOrder = new AV.Query('Shop_order');
    shopOrder.equalTo("scoreFightGroupsOId", fightGroupOId);
    shopOrder.notContainedIn("status",[0,1]);
    shopOrder.limit(1000);
    return shopOrder.count().then(count=>{
        return count
    }).catch(error=>{
        console.log(error)
        return 0
    })
}

exports.sameGroupOrder = sameGroupOrder;
async function  sameGroupOrder(req) {
    let pageIndex = req.body.pageIndex;
    let pageSize =  req.body.pageSize;
    let groupOId =  req.body.groupOId;

    let buyerOId=req.body.buyerOId
    let receiver=req.body.receiver
    let orderCode=req.body.orderCode
    let buyerNickName=req.body.buyerNickName
    let orderStatus=req.body.orderStatus

    console.log("pageIndex-->"+pageIndex)
    console.log("pageSize-->"+pageSize)
    console.log("groupOId-->"+groupOId)
    console.log("buyerOId-->"+buyerOId)
    console.log("receiver-->"+receiver)
    console.log("orderCode-->"+orderCode)
    console.log("buyerNickName-->"+buyerNickName)
    console.log("orderStatus-->"+orderStatus)

    if (pageIndex == '' || !pageIndex||pageIndex==0 ) {
        pageIndex = 1;
    } else {
        pageIndex = parseInt(pageIndex);
    }
    if (pageSize == '' || !pageSize) {
        pageSize = 20;
    } else {
        pageSize = parseInt(pageSize);
    }
    console.log("2pageIndex-->"+pageIndex)
    var query=new AV.Query('Shop_order');


    query.equalTo("scoreFightGroupsOId", groupOId);

    if(buyerOId!=""&&buyerOId){
        query.equalTo("buyerOId",buyerOId)
    }
    if(receiver!=""&&receiver){
        query.equalTo("receiver",receiver)
    }
    if(orderCode!=""&&orderCode){
        query.equalTo("orderCode",orderCode)
    }
    if(buyerNickName!=""&&buyerNickName){
        let userOIds=await getUserOIdByNickName(buyerNickName)
        if(userOIds&&userOIds.length>0){
            query.containedIn("buyerOId",userOIds)
        }
    }

    if(orderStatus!=""&&orderStatus&&orderStatus!=100){
        query.equalTo("status",orderStatus)
    }

    query.include('shopObj');
    query.include('sellerObj');
    query.include('userObj');
    query.limit(pageSize);
    query.skip((pageIndex - 1) * pageSize);
    query.descending('createdAt');

    return query.find().then(result=>{
        return query.count().then(async count=>{
            let obj = {};
            let data = [];
            for (let item of result) {
                let temObj = {};
                temObj.objectId=item.get("objectId")
                temObj.orderStatus=item.get("status")
                temObj.orderCode=item.get("orderCode")
                temObj.receiver=item.get("receiver")
                temObj.payTime=item.get("payTime")
                temObj.totalPrice=item.get("totalPrice")
                temObj.phone=item.get("phone")
                temObj.payType=item.get("payType")
                temObj.createdAt = moment(item.get("createdAt")).format('YYYY-MM-DD HH:mm:ss');
                temObj.address= item.get("address");
                temObj.expressCode= item.get("expressCode");
                temObj.logisticsCom= item.get("logisticsCom");
                temObj.deliverTime= item.get("deliverTime");
                temObj.sellerOId= item.get("sellerOId");
                let shopObj=item.get("shopObj")
                temObj.shopName= shopObj?shopObj.get("name") : '';
                temObj.shopUserName= item.get("sellerObj") ? item.get("sellerObj").get("nickName") : '';

                let buyerObj=item.get("buyerObj")
                temObj.buyerId = buyerObj ? buyerObj.get("objectId") : '';
                temObj.buyerName = buyerObj ? buyerObj.get("nickName") : '';

                temObj.status=item.get("status")

                let shopOrderGoods=await getShopOrderGoods(temObj.objectId)
                if(shopOrderGoods!=""&&shopOrderGoods){
                    let goodsOId={}
                    goodsOId.status="app"
                    goodsOId.objectId=shopOrderGoods.get("goodsOId");
                    temObj.goodsOId=goodsOId

                    temObj.num=shopOrderGoods.get("num")
                    temObj.goodsOriginPrice = shopOrderGoods.get("goodsOriginPrice");
                    temObj.goodsModel = shopOrderGoods.get("goodsModel");
                    temObj.goodsName= shopOrderGoods.get("goodsName");
                    temObj.goodsPicURL = shopOrderGoods.get("goodsPicURL") ? shopOrderGoods.get("goodsPicURL") : "";
                    temObj.price = shopOrderGoods.get("price");
                }

                let incomMoney = await whereMoneyAdd(orderCode) + item.get("fare");
                let totalPrice = item.get("totalPrice");
                incomMoney = Math.round(incomMoney * 100);
                totalPrice = Math.round(totalPrice * 100);
                if (incomMoney == totalPrice || temObj["status"] == 1) {
                    temObj["moneyStatus"] = 1;
                } else {
                    temObj["moneyStatus"] = 0;
                }

               console.log("finish-->"+temObj.orderOId)
                data.push(temObj);
            }
            obj.data = data;
            obj.total = count;
            return obj;
        }).catch(error=>{
            console.log(error)
            return null;
        })
    }).catch(error=>{
        console.log(error)
        return null;
    })

    function whereMoneyAdd(orderNo) {
        let moneyQuery = new AV.Query("Shop_account_detail");
        moneyQuery.equalTo("orderNo", Number(orderNo));
        let MoneyQuery = moneyQuery.find().then((result) => {
            let money = 0;
            for (let i = 0; i < result.length; i++) {
                money = money + Number(result[i].get("changeMoney"));
            }
            return money;
        })
        return MoneyQuery;
    }
}

// // //物流信息
// // var temObj = {};
// // temObj["goodsOId"] = {};
// let incomMoney = await whereMoneyAdd(temObj["orderCode"]) + order.get("fare");
// let totalPrice = order.get("totalPrice");
// incomMoney = Math.round(incomMoney * 100);
// totalPrice = Math.round(totalPrice * 100);
// if (incomMoney == totalPrice || temObj["status"] == 1) {
//     temObj["moneyStatus"] = 1;
// } else {
//     temObj["moneyStatus"] = 0;
// }



function getShopOrderGoods(orderOId){
    var goodsQuery = new AV.Query('Shop_order_goods')
    goodsQuery.equalTo("orderOId",orderOId)
    return goodsQuery.first().then(result=>{
        return result
    }).catch(error=>{
        console.log(error)
        return null
    })
}

function getUserOIdByNickName(nickName){
    let query=new AV.Query("_User")
    query.contains("nickName",nickName)
    query.find().then(result=>{
        if(result==""||!result){
            return false
        }
        let ids=[]
        for(let item of result){
            ids.push(item.id)
        }
        return ids
    }).catch(error=>{
        console.log(error)
        return false
    })

}

exports.getWalletInfo = getWalletInfo;
function  getWalletInfo(data) {
  var page = data.page
  var num = data.num
  if(page == '' || page == undefined || page == null){
    page = 1;
  }else{
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 20
  } else {
    num = parseInt(num)
  }
  let query = new AV.Query('Wallet_Info');
  query.limit(num);
  query.skip((page - 1)* num);
  query.include('userObj')
  query.descending("createAt");
  return  query.find().then(function (result) {
    return query.count().then(function (count) {
      let obj = {};
      let data = [];
      for (let item of result) {
        let temObj = {};
        temObj["objectId"] = item.get("objectId");
        temObj["userOId"] = item.get("userOId");
        temObj["nickName"] = item.get("userObj").get('nickName');
        temObj["walletAddress"] = item.get("walletAddress");
        temObj["tokenType"] = item.get("tokenType");
        temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
        temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
        data.push(temObj);
      }
      obj.data = data;
      obj.total = count;
      return obj;
    }).catch(err=>{
      console.log(err)
    })
  }).catch(error=>{
    console.log(error)
  })
}
exports.walletAddressAdd = walletAddressAdd;
async function walletAddressAdd(req) {
  // console.log(req)
  let userOId = req.userOId
  let userObj = AV.Object.createWithoutData("_User", req.userOId);
  let address = req.address
  let WalletInfo = AV.Object.extend('Wallet_Info');
  let walletInfo = new WalletInfo();
  walletInfo.set('userOId',userOId);
  walletInfo.set('userObj',userObj);
  walletInfo.set('walletAddress',address);
  walletInfo.set('tokenType',req.tokenType);
  return walletInfo.save().then(result=>{
    if (result){
      return result.get('userOId')
    }
  }).catch(error=>{
    console.log(error)
  })
}

exports.walletAddressRemove = walletAddressRemove;
async function walletAddressRemove(objectId) {
  let query = AV.Object.createWithoutData('Wallet_Info', objectId);
  return query.destroy().then(resolve => {
    return resolve.id
  }).catch(error => {
    console.log(error)
  })
}
exports.getWalletInfoForId = getWalletInfoForId;
function getWalletInfoForId(objectId,callback) {
  let query = new AV.Query('Wallet_Info');
  if (objectId != "" && objectId != undefined && objectId != null) {
    query.equalTo("objectId", objectId);
  } else {
    callback("没有objectId，无法继续操作！", "null");
  }
  query.include('userObj')
  query.first().then(result=>{
    if (result){
      let temObj = {};
      temObj["objectId"] = result.get("objectId");
      temObj["userOId"] = result.get("userOId");
      temObj["nickName"] = result.get("userObj").get('nickName');
      temObj["tokenType"] = result.get("tokenType");
      temObj["walletAddress"] = result.get("walletAddress");
      callback("null", temObj);
    } else {
      callback("未找到该信息", "null");
    }
  }).catch(error=>{
    console.log(error)
  })
}
exports.getWalletTokenType = getWalletTokenType;
function getWalletTokenType(callback) {
  let query = new AV.Query('Dictionary');
  query.equalTo("type", '13');
  query.find().then(results=>{
    if (results){
      let data = [];
      for (let item of results) {
        var temObj = {};
        temObj["id"] = item.get("code");
        temObj["text"] = item.get("name");

        data.push(temObj);
      }
      callback(data)
    }
  }).catch(error=>{
    console.log(error)
  })
}

exports.queryAddressPageTx = queryAddressPageTx;
async function queryAddressPageTx(data,callback) {
  let pageNum = data.page
  let pageSize = data.num
  let walletAddress = data.walletAddress
  let url = 'http://www.aladada.com:14440/lightWallet/queryAddressPageTx?address='+ walletAddress +'&pageSize=' + pageSize + '&pageNum=' + pageNum
  request({
    method: 'GET',
    url: url,
    headers: {
      'Content-Type': 'application/json'
    }
  }, function (err, res, body) {
    if (err) {
      console.log(err)
    } else {
      if (res.statusCode == '200'){
        // console.log(res.statusCode)
        // console.log(JSON.parse(body).data)
        let results = JSON.parse(body).data
        let obj = {};
        let data = []
        for (let item of results) {
          var temObj = {};
          temObj["amount"] = Number(item.amount)/1000; //交易总额
          temObj["fee"] = Number(item.fee)/1000; //交易费用
          if(item.amountAssetId == '3'){
            temObj["amountAssetId"] = 'TEC'; //交易币种 Token
          } else if (item.amountAssetId == '0'){
            temObj["amountAssetId"] = 'ISC'; //交易币种 Token
            temObj["amount"] = Number(item.amount)/100000; //交易总额
          } else {
            temObj["amountAssetId"] = item.amountAssetId; //交易币种 Token
          }

          temObj["trxId"] = item.trxId; //交易单号
          temObj["fromAccount"] = item.fromAccount; //来源钱包地址
          temObj["toAccount"] = item.toAccount; //去向钱包地址
          temObj["trxTimes"] = moment(item.trxTimes).format('YYYY年MM月DD HH:mm:ss');; //交易时间

          data.push(temObj);
        }
        obj.data = data;
        obj.total = JSON.parse(body).dataTotal;
        // console.log(obj)
        callback(obj)
      } else {
        console.log('获取交易记录失败，错误代码：'+res.statusCode)
      }
    }
  });
}

exports.distributeToken = distributeToken;
async function distributeToken(data,callback) {
  let tokenType = data.tokenType
  let toAddress = data.walletAddress
  let amount = data.amount
  // console.log(toAddress,tokenType,amount)
  let url = 'http://www.aladada.com:14440/issue-wallet/transfer'
  request({
    method: 'POST',
    url: url,
    json: true,
    headers: {
      'Content-Type': 'application/json'
    },
    body:{
      "coinType": tokenType,
      "payAccountName": "hello",
      "toAddress": toAddress,
      "value": amount,
      "walletName": "center",
      "walletPassword": "a6666666"
    }
  }, function (err, res, body) {
    if (err) {
      console.log(err)
    } else {
      // console.log(res.statusCode)
      // console.log(body.targetAddress)
      if (res.statusCode == '200'){
        callback(body.targetAddress)
      } else {
        console.log('发币失败，错误代码：'+res.statusCode)
      }
    }
  });
}

exports.getExternalGoodsInfo = getExternalGoodsInfo;
function  getExternalGoodsInfo(data) {
  let page = data.page
  let num = data.num
  let sourceGoodsName = data.sourceGoodsName
  let status = data.status
  let goodsSource = data.goodsSource
  let goodsTypeOId = ''
  let goodsTypePId = ''
  if (data.goodsTypeOId){
    goodsTypeOId = data.goodsTypeOId
  } else {
    goodsTypeOId = ''
  }
  if (data.goodsTypePId){
    goodsTypePId = data.goodsTypePId
  } else {
    goodsTypePId = ''
  }
  var query = new AV.Query('External_goods');
  if(page == '' || page == undefined || page == null){
    page = 1;
  }else{
    page = parseInt(page);
  }
  if (num == '' || num == undefined || num == null) {
    num = 20
  } else {
    num = parseInt(num)
  }

  if (sourceGoodsName == '' || sourceGoodsName ==  undefined || sourceGoodsName ==  null) {
  } else {
    query.contains('sourceGoodsName',sourceGoodsName)
  }
  if (goodsSource == '' || goodsSource ==  undefined || goodsSource ==  null) {
  } else {
    query.equalTo('goodsSource',goodsSource)
  }
  if (goodsTypePId == '' && goodsTypeOId != ''){
    query.equalTo('shopGoodsTypeParentOId',goodsTypeOId)
  }
  if (goodsTypePId != '' && goodsTypeOId != '') {
    query.equalTo('shopGoodsTypeOId',goodsTypeOId)
    query.equalTo('shopGoodsTypeParentOId',goodsTypePId)
  }
  if (status == '' || status ==  undefined || status ==  null || status ==  NaN) {
  } else {
    query.equalTo('status',Number(status))
  }

  query.limit(num);
  query.skip((page - 1)* num);
  query.descending("createAt");
  query.include('shopGoodsTypeObj')
  query.include('shopGoodsTypeParentObj')
  return  query.find().then(function (result) {
    return query.count().then(function (count) {
      let obj = {};
      let data = [];
      for (let item of result) {
        let temObj = {};
        temObj["objectId"] = item.get("objectId");
        temObj["goodsSource"] = item.get("goodsSource");
        temObj["sourceGoodsId"] = item.get("sourceGoodsId");
        temObj["sourceGoodsName"] = item.get("sourceGoodsName");
        temObj["sourceGoodsIcon"] = item.get("sourceGoodsIcon");
        temObj["sourceGoodsDetailUrl"] = item.get("sourceGoodsDetailUrl");
        temObj["sourceShopName"] = item.get("sourceShopName");
        temObj["price"] = item.get("price");
        temObj["SalesVolumeMonth"] = item.get("SalesVolumeMonth");
        temObj["commissionRatio"] = item.get("commissionRatio");
        temObj["commission"] = item.get("commission");
        temObj["sellerServices"] = item.get("sellerServices");
        temObj["shareUrl"] = item.get("shareUrl");
        temObj["status"] = item.get("status");
        let parentGoodsTypeName = item.get('shopGoodsTypeParentObj') ? item.get('shopGoodsTypeParentObj').get('name') : '';
        let goodsTypeName = item.get('shopGoodsTypeObj') ? item.get('shopGoodsTypeObj').get('name') : '';
        if (parentGoodsTypeName != '' && goodsTypeName != ''){
          temObj['goodsType'] = parentGoodsTypeName + '-' + goodsTypeName;
        } else {
          temObj['goodsType'] = parentGoodsTypeName;
        }
        temObj["shopGoodsTypeOId"] = item.get('shopGoodsTypeOId');
        temObj["shopGoodsTypeParentOId"] = item.get('shopGoodsTypeParentOId');
        temObj["updatedAt"] = moment(item.updatedAt).format('YYYY年MM月DD HH:mm:ss');
        temObj["createdAt"] = moment(item.createdAt).format('YYYY年MM月DD HH:mm:ss');
        data.push(temObj);
      }
      obj.data = data;
      obj.total = count;
      return obj;
    }).catch(err=>{
      console.log(err)
    })
  }).catch(error=>{
    console.log(error)
  })
}

exports.removeExternalGoods = removeExternalGoods;
async function removeExternalGoods(data) {
  let objectId = data.objectId
  let status = Number(data.status)
  let goodsObj = AV.Object.createWithoutData('External_goods', objectId);
  goodsObj.set('status',status)
  return goodsObj.save().then(result => {
    return result.id
  }).catch(error => {
    console.log(error)
  })
}
exports.excelUpload = excelUpload;
async function excelUpload(data) {
  let uploadFilePath = data.uploadFilePath;
  let uploadFileName = data.uploadFileName
  let goodsSource = data.goodsSource;
  let goodsTypeOId = data.goodsTypeOId;
  let goodsTypePId = data.goodsTypePId;
  // console.log(`${__dirname}`)
  // console.log(uploadFilePath)
  // console.log(uploadFileName)
  // console.log('excelUploadData',data)
  const buffer = fs.readFileSync(uploadFilePath)
  const result = JSON.parse(JSON.stringify(xlsx.parse(buffer)));
  const array = []
  let list = result[0].data.slice(1)
  var External_goods = AV.Object.extend('External_goods');

  for (let item of list) {
    let externalGoods = await getExistsGoodsObj((item[0] + "").trim())
    if (!externalGoods){
      externalGoods = new External_goods()
    }
    externalGoods.set('goodsSource', goodsSource)
    externalGoods.set('status', 0)
    var goodsTypeObj = AV.Object.createWithoutData('Shop_good_type', goodsTypeOId);
    if (goodsTypePId != null && goodsTypePId != '') {
      let goodsTypePObj = AV.Object.createWithoutData('Shop_good_type', goodsTypePId);
      externalGoods.set('shopGoodsTypeParentOId', goodsTypePId);
      externalGoods.set('shopGoodsTypeParentObj', goodsTypePObj);
      externalGoods.set('shopGoodsTypeOId', goodsTypeOId);
      externalGoods.set('shopGoodsTypeObj', goodsTypeObj);
    } else {
      externalGoods.set('shopGoodsTypeParentOId', goodsTypeOId);
      externalGoods.set('shopGoodsTypeParentObj', goodsTypeObj);
    }
    if (goodsSource == '淘宝'){
      externalGoods.set('sourceGoodsId', (item[0] + "").trim())
      externalGoods.set('sourceGoodsName', (item[1] + "").trim())
      externalGoods.set('sourceGoodsIcon', (item[2] + "").trim())
      externalGoods.set('sourceGoodsDetailUrl', (item[3] + "").trim())
      externalGoods.set('sourceShopName', (item[4] + "").trim())
      externalGoods.set('price', Number((item[5] + "").trim()))
      externalGoods.set('SalesVolumeMonth', Number((item[6] + "").trim()))
      externalGoods.set('commissionRatio', Number((item[7] + "").trim()))
      externalGoods.set('commission', Number((item[8] + "").trim()))
      externalGoods.set('sellerServices', (item[9] + "").trim())
      externalGoods.set('shareUrl', (item[11] + "").trim())
    } else if (goodsSource == '京东'){
      externalGoods.set('sourceGoodsName', (item[0] + "").trim())
      externalGoods.set('sourceGoodsDetailUrl', (item[1] + "").trim())
      externalGoods.set('SalesVolumeMonth', Number((item[2] + "").trim()))
      externalGoods.set('price', Number((item[3] + "").trim()))
      externalGoods.set('commissionRatio', Number((item[4] + "").trim()))
      externalGoods.set('commission', Number((item[5] + "").trim()))
      externalGoods.set('shareUrl', (item[9] + "").trim())
    }
    array.push(externalGoods)
  }
    return AV.Object.saveAll(array).then(results=>{
      if (results) {
        return results
      } else {
        console.log('保存失败！')
        return
      }
    }).catch(error=>{
      console.log(error)
    })
}
function getExistsGoodsObj(sourceGoodsId) {
  let query = new AV.Query('External_goods')
  query.equalTo('sourceGoodsId', sourceGoodsId)
  return query.first().then(result=>{
    return result
  }).catch(error=>{
    console.log(error)
    return
  })
}